反转defaultdict(dict)

时间:2017-05-14 19:38:49

标签: python reverse graph-theory directed-graph defaultdict

如果我有一个defaultdict(dict):

defaultdict("dict"), {'NYC': {'LA': '3000'}, 'SanFrancisco': {'Houston': '1000'}, 'LA': {'Detroit': '200', 'Ames': '300', 'SanFrancisco': True}, 'Austin': {'Houston': '500'}})

我怎样才能“扭转弧线”?或者从这个网站的第3步? http://www.geeksforgeeks.org/connectivity-in-a-directed-graph/

示例输出:

# edited for more clarity
defaultdict(<class 'dict'>,
            {'Ames': {'LA': '300'},
             'Detroit': {'LA': '200'},
             'Houston': {'Austin': '500', 'SanFrancisco': '1000'},
             'LA': {'NYC': '3000'},
             'SanFrancisco': {'LA': True}})

转置图表:https://en.wikipedia.org/wiki/Transpose_graph

P.S。我想将我的反转图保持为defaultdict(dict)。谢谢!

1 个答案:

答案 0 :(得分:3)

嵌套的defaultdict是一个二维数据结构(对于每个源城市,可能有多个目的地)。因此,使用嵌套的for循环来遍历数据并重新插入新的 defaultdict 并使尺寸反转(交换源和目标)是有意义的:

>>> from collections import defaultdict

>>> start = defaultdict(dict, {'NYC': {'LA': '3000'}, 'SanFrancisco': {'Houston': '1000'}, 'LA': {'Detroit': '200', 'Ames': '300', 'SanFrancisco': True}, 'Austin': {'Houston': '500'}})

>>> goal = defaultdict(dict)
>>> for source, dests in start.items():
        for dest, distance in dests.items():
            goal[dest][source] = distance

>>> goal
defaultdict(<class 'dict'>, {'LA': {'NYC': '3000'}, 'Houston': {'SanFrancisco': '1000', 'Austin': '500'}, 'Detroit': {'LA': '200'}, 'Ames': {'LA': '300'}, 'SanFrancisco': {'LA': True}})