简体   繁体   中英

Adjacency list from Python dict

I need to output a Python dictionary as an adjacency list: two columns, one – key, other – value; like this:

Key1, Value1
Key2, Value2

My dict contains strings as keys and integers as values. Was hoping that these lines would do the trick:

with open('Adjacency_list_indegrees.csv', 'wb') as ff:
    ff.write('\n')
    for key, values in deg_new.items():
        for value in values:
            ff.write('{},{}'.format(key, value))
            ff.write('\n')

However, I'm getting an error

 TypeError: 'int' object is not iterable

Does it mean that I have to transform integer values?

You are trying to loop over the values, which are integers and not lists. You don't need to do that at all here; simplify your list to:

for key, value in deg_new.items():
    ff.write('{},{}\n'.format(key, value))

You also appear to be reinventing the wheel; there is a perfectly serviceable csv module for this task:

import csv

with open('Adjacency_list_indegrees.csv', 'wb') as ff:
    writer = csv.writer(ff)
    ff.writerows(deg_new.items())

This writes all key-value pairs from deg_new in one go.

deg_new.items() will give you key, value pairs from your dictionary.

Eg

key1, value1
key2, value2
...

You don't have to then try and iterate through the values; you are already getting them one at a time.

So you can do this:

for key, value in deg_new.items():
    ff.write('{},{}\n'.format(key, value))

There are probably some values that are not lists/tuples, rather are ints. For these instances you should use try .. except . Try the below code:

with open('Adjacency_list_indegrees.csv', 'wb') as ff:
    ff.write('\n')
    for key, values in deg_new.items():
        try:
            for value in values:
                ff.write('{},{}'.format(key, value))
                ff.write('\n')
        except:
            ff.write('{},{}'.format(key, values))
            ff.write('\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM