Search code examples
pythoncsvdictionarykeyenumerate

Keys of a dictionary of lists to a row-enumerated, tab-delimited csv file


My dictionaries that include names of characters and their offsets look like this:

{'Amestris': [(2247, 2255)],
     'Beda': [(3266, 3270)],
     'Fuery': [(2285, 2290),
               (2380, 2385),
               (2686, 2691),
               (2723, 2728),
     'Gloria': [(1565, 1571)],
     'Hawkeye': [(22, 29),
                 (832, 839),
                 (999, 1006),
                 (1119, 1126),
                 (1927, 1934),
                 (3007, 3014),
                 (4068, 4075)]}

My desired output would be the keys of the dictionary (the character names).

In addition, the first column should be enumerating the character names as their Ids, starting from 0.

The tab-delimited csv file should look like this:

Id  Label
0  Amestris
1  Beda
2  Fuery
3  Gloria
4  Hawkeye

So far I've reached this point:

import csv
import pickle

exmen = pickle.load(open("exmen.p", "rb"))

with open('mycsvfile.csv', 'w') as f:
    i = 0
    fieldnames = ['Id', 'Label']
    w = csv.writer(f, delimiter=' ', fieldnames=fieldnames)
    w.writeheader()
    w.writerow(i(dict(fieldnames, (key))) for key in exmen)

I'm getting this error message:

line 28, in <module>
    w = csv.writer(f, delimiter=' ', fieldnames=fieldnames)

TypeError: 'fieldnames' is an invalid keyword argument for this function

I'm not sure how to include the headers Id and Label other than using fieldnames and how to implement the enmuerating of the rows, here I tried to apply i = 0 and tried to find somewhere in the last line to apply an i += 1 but it gave me the error warning syntax error

Any ideas for improving the code?

Thanks in advance!


Solution

  • fieldnames is only an argument for csv.DictWriter which you do not need here. You could try sth. along the following lines, using csv.writer:

    with open('mycsvfile.csv', 'w') as f:
        w = csv.writer(f, delimiter='\t')  # tab delimited
        w.writerow(['Id', 'Label'])        # just write header row
        w.writerows(enumerate(exmen))      # write (id, key) rows
    

    If exmen is common dict, there is no guarantee of the keys' order. You can do:

        w.writerows(enumerate(sorted(exmen)))
    

    to enforce alphabetical order.