[英]Converting paired list values to dictionary
I have a list of pairs like the following one:我有一个配对列表,如下所示:
[['A', 'B'],
['C', 'E'],
['F', 'D'],
['C', 'D'],
['D', 'E'],
['G', 'E'],
['B', 'A'],
['H', 'G'],
['A', 'F'],
['E', 'A']]
I want to generate a dictionary with the first value in each pair as keys and the second one as value like the following:我想生成一个字典,其中每对中的第一个值作为键,第二个作为值,如下所示:
{'A': ['B', 'F'],
'B': ['A'],
'C': ['E', 'D'],
'D': ['E'],
'E': ['A'],
'F': ['D', 'E'],
'G': ['E'],
'H': ['G']}
I used the following code, but didn't reached the desired outcome:我使用了以下代码,但没有达到预期的结果:
keys = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
graph = {}
graph = graph.fromkeys(keys, [])
for row in pairs:
(graph[row[0]]).append(row[1])
dict.fromkeys
will set all your values to the same list object! dict.fromkeys
会将您的所有值设置为同一个列表对象! Usedict.setdefault
instead which will create a new list for each unknown key:使用
dict.setdefault
代替它将为每个未知键创建一个新列表:
graph = {}
for row in pairs:
graph.setdefault(row[0], []).append(row[1])
Alternatively, use a collection.defaultdict
或者,使用
collection.defaultdict
from collections import defaultdict
graph = defaultdict(list)
for row in pairs:
graph[row[0]].append(row[1])
Or, more elegantly:或者,更优雅地:
for v1, v2 in in pairs:
graph[v1].append(v2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.