简体   繁体   English

Python dict的邻接列表

[英]Adjacency list from Python dict

I need to output a Python dictionary as an adjacency list: two columns, one – key, other – value; 我需要输出一个Python字典作为邻接表:两列,一列-键,另一列-值; 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: 有一个完美可维护的csv模块可以完成此任务:

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写入deg_new中的所有键值对。

deg_new.items() will give you key, value pairs from your dictionary. deg_new.items()将为您提供字典中的键,值对

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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