首页 文章

使用分数从字典创建有向图

提问于
浏览
2

我有这本字典:

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

它是一种有向图 . 例如,d1 ['a']指向“b”两次,一次指向“c”(见下图)

我想要的是从d1-pointing_to和pointed_by创建两个字典,其值分别描述它们指向或指向的次数 .

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

1 回答

  • 5

    您可以使用一些collections utils来获取输出:

    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)
    

相关问题