python reverse / transpose一本字典

时间:2014-04-21 18:46:14

标签: python dictionary

我希望在python上转换字典,在环顾四周之后,我无法为此解决问题。有谁知道我怎么能像以下那样反转字典作为输入:

graph = {'A': ['B', 'C'],
             'B': ['C', 'D'],
             'C': ['D'],
             'D': ['C'],
             'E': ['F'],
             'F': ['C']}

所以我得到类似的东西:

newgraph = {'A': [''],
         'B': ['A'],
         'C': ['A', 'B', 'D','F'],
         'D': ['B', 'C'],
         'E': [''],
         'F': ['E']}

3 个答案:

答案 0 :(得分:2)

使用defaultdict

newgraph = defaultdict(list)
for x, adj in graph.items():
    for y in adj:
        newgraph[y].append(x)

虽然在空列表中使用空字符串''似乎没有任何意义,但它当然是可能的:

for x in newgraph:
    newgraph[x] = newgraph[x] or ['']

答案 1 :(得分:0)

使用defaultdict

>>> from collections import defaultdict
>>> graph = {'A': ['B', 'C'],
...              'B': ['C', 'D'],
...              'C': ['D'],
...              'D': ['C'],
...              'E': ['F'],
...              'F': ['C']}
>>> new_graph = defaultdict(list)
>>> for ele in graph.keys():
...     new_graph[ele] = []
...
>>> for k, v in graph.items():
...     for ele in v:
...             new_graph[ele].append(k)
...
>>> pprint(new_graph)
{'A': [],
 'B': ['A'],
 'C': ['A', 'B', 'D', 'F'],
 'D': ['B', 'C'],
 'E': [],
 'F': ['E']}

答案 2 :(得分:0)

没有defaultdict也是可能的。 在这里,我将新的dict中的空键留下,值为None。

graph = {'A': ['B', 'C'],
             'B': ['C', 'D'],
             'C': ['D'],
             'D': ['C'],
             'E': ['F'],
             'F': ['C']}

g = dict.fromkeys(graph.keys())
for k, v in graph.iteritems():
  for x in v:
    if g[x]: g[x] += [k]
    else:    g[x] = [k]

for k in sorted(graph.keys()):
  print k, ':', g[k]

输出:

A : None
B : ['A']
C : ['A', 'B', 'D', 'F']
D : ['C', 'B']
E : None
F : ['E']