0

i have a dictionary like this : (i,m using Python 3.9)

myDict = {'hamid': 25,
'john' : 15,
'mike': 14.666666666666666
'tim': 16.6
'joana': 13.666666666666666
'hana': 10.666666666666666
}

the values in the dictionary must be integer

i wanna write each item in a row of a csv file named Results.csv and must be exactly like this : (each key and it's value in a single line of the csv file )

hamid,25
john,15
mike,14.666666666666666
tim,16.6
joana,13.666666666666666
hana,10.666666666666666

and for the second issue :

how can i write 3 of them which have higher values ( descending 3 of them ) like this :

hamid,25
john,15
tim,16.6

or Ascending 3 of them like this :

mike,14.666666666666666
joana,13.666666666666666
hana,10.666666666666666

THE VALUES SHOULDN,T BE ROUNDED

thanks

Curious guy
  • 13
  • 1
  • 8
  • First: that are not only integers in your dictionary. Second: for csv writing follow https://docs.python.org/3/library/csv.html#module-contents – chillking May 27 '21 at 08:09
  • Dictionaries are order independent. Strictly speaking, there will be no guarantee that your output file preserves the order you define the items in the dictionary. If you really need to keep the row order as-is, use other data structures such as list or tuple. – Kota Mori May 27 '21 at 12:49

1 Answers1

0

I think this will work.

import csv
from os import read
myDict = {'hamid': 25,
'john' : 15,
'mike': 14.666666666666666,
'tim': 16.6,
'joana': 13.666666666666666,
'hana': 10.666666666666666
}
with open("Data.csv","w") as file:
    reader=csv.writer(file)
    for value,item in myDict.items():
        reader.writerow((value,item))

Here is the output:

hamid,25

john,15

mike,14.666666666666666

tim,16.6

joana,13.666666666666666

hana,10.666666666666666

For sorting the dictionary:

MyDict = sorted(myDict.items(), key=lambda x: x[1], reverse=True)
print(MyDict)

  • ok, thanks, but in output file, there is a empty line between each entered line and i dont want it, how can i fix it? – Curious guy May 27 '21 at 08:58
  • As to the empty lines, check this out. https://stackoverflow.com/questions/3191528/csv-in-python-adding-an-extra-carriage-return-on-windows – Kota Mori May 27 '21 at 12:47