Skip to content Skip to sidebar Skip to footer

Possibility Of Writing Dictionary Items In Columns

i have a dictionary in which keys are tuples and values are list like {('c4:7d:4f:53:24:be', 'ac:81:12:62:91:df'): [5.998999999999998,0.0013169999, 4.0000000000000972], ('a8:5

Solution 1:

import csv

mydict = {('c4:7d:4f:53:24:be', 'ac:81:12:62:91:df'):
          [5.998999999999998, 0.0013169999, 4.0000000000000972],
          ('a8:5b:4f:2e:fe:09', 'de:62:ef:4e:21:de'):
          [7.89899999, 0.15647999999675390, 8.764380000972, 9.200000000]}

withopen('dict.csv', 'wb') as file:
    writer = csv.writer(file, delimiter='\t')
    writer.writerow(mydict.keys())
    for row inzip(*mydict.values()):
        writer.writerow(list(row))

Output file dict.csv:

('c4:7d:4f:53:24:be', 'ac:81:12:62:91:df')  ('a8:5b:4f:2e:fe:09', 'de:62:ef:4e:21:de')
5.998999999999998   7.89899999
0.0013169999    0.1564799999967539
4.000000000000097   8.764380000972

Solution 2:

I am sure you can figure out the formatting:

>>> d.keys() #gives list of keys for first row
[('c4:7d:4f:53:24:be', 'ac:81:12:62:91:df'), ('a8:5b:4f:2e:fe:09', 'de:62:ef:4e:21:de')]
>>> for i inzip(*d.values()):  #gives rows with tuple structure for columnsprint i
(5.998999999999998, 7.89899999)
(0.0013169999, 0.1564799999967539)
(4.000000000000097, 8.764380000972)

For your code, do this:

writer = csv.writer(open('dict.csv', 'wb'))
writer.writerow(mydict.keys())  
forvalues in zip(*mydict.values()):
    writer.writerow(values)

The ()'s and such will not be added to the csv file.

Post a Comment for "Possibility Of Writing Dictionary Items In Columns"