2

I have this dictionary:

d1={
'a':['b','c','b'],
'b':['a','d','e']
}

it is sort of a directed graph. For example, d1['a'] points twice to 'b', and once to 'c' (see graph below)

enter image description here

What I want is to create two dictionaries out of d1 - pointing_to and pointed_by with values describing how many times they are pointing to or pointed by, respectively.

pointing_to={
'a':{'b':2,'c':1},
'b':{'a':1,'d':1,'e':1},
}

pointed_by={
'a':{'b':1},
'b':{'a':2},
'c':{'a':1},
'd':{'b':1},
'e':{'b':1}
}
4

1 回答 1

5

您可以使用一些实用collections程序来获取您的输出:

from collections import Counter, defaultdict

d1 = {'a': ['b', 'c', 'b'], 'b': ['a', 'd', 'e']}

pointed_to = {k: Counter(v) for k, v in d1.items()}
pointed_from = defaultdict(dict)
for k, v in pointed_to.items():
    for k_, v_ in v.items():
        pointed_from[k_][k] = v_

# pointed_to
{'a': Counter({'b': 2, 'c': 1}), 
 'b': Counter({'d': 1, 'a': 1, 'e': 1})}

# pointed_from
defaultdict(<class 'dict'>, {'d': {'b': 1}, 
                             'a': {'b': 1}, 
                             'c': {'a': 1}, 
                             'b': {'a': 2}, 
                             'e': {'b': 1}})

请注意,Counterdeafultdict都是 的子类dict,因此出于所有意图和目的,这两个都可以用作您所需的输出字典。

如果你真的想要dict对象,你可以很容易地做到这一点:

pointed_to = {k: dict(v) for k, v in pointed_to.items()}
pointed_from = dict(pointed_from)
于 2018-12-09T23:00:17.700 回答