Zlo
Zlo

Reputation: 1170

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?

Upvotes: 0

Views: 473

Answers (3)

Irshad Bhat
Irshad Bhat

Reputation: 8709

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')

Upvotes: 0

khelwood
khelwood

Reputation: 59096

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

E.g.

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))

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121226

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.

Upvotes: 1

Related Questions