在python中合并3个dict()

时间:2012-12-05 07:51:54

标签: python dictionary

是否有一种逻辑合并多个词典的方法,如果它们之间有共同的字符串?即使这些常见字符串在一个dict()的值与另一个的键之间匹配吗?

我在SO上看到很多类似的问题,但似乎没有解决我将“低级文件”中的多个键与高级键/值(level1dict)中的多个键相关联的具体问题

说我们有:

level1dict = { '1':[1,3], '2':2 }
level2dict = { '1':4, '3':[5,9], '2':10 }
level3dict = { '1':[6,8,11], '4':12, '2':13, '3':[14,15], '5':16, '9':17, '10':[18,19,20]}
finaldict = level1dict

当我在逻辑上说我的意思是,在level1dict 1 = 1,3而在level2dict 1 = 4和3 = 5,9所以整体(到目前为止)1 = 1,3,4,5,9(排序不重要)

我想要的结果是

#.update or .append or .default?
finaldict = {'1':[1,3,4,5,9,6,8,11,12,14,15,16,17] '2':[2,10,18,19,20]}

回答:谢谢Ashwini Chaudhary和Abhijit的网络x模块。

3 个答案:

答案 0 :(得分:9)

这是连接组件子图的问题,如果要使用networkx,可以最好地确定。这是您的问题的解决方案

>>> import networkx as nx
>>> level1dict = { '1':[1,3], '2':2 }
>>> level2dict = { '1':4, '3':[5,9], '2':10 }
>>> level3dict = { '1':[6,8,11], '4':12, '2':13, '3':[14,15], '5':16, '9':17, '10':[18,19,20]}
>>> G=nx.Graph()
>>> for lvl in level:
    for key, value in lvl.items():
        key = int(key)
        try:
            for node in value:
                G.add_edge(key, node)
        except TypeError:
            G.add_edge(key, value)


>>> for sg in nx.connected_component_subgraphs(G):
    print sg.nodes()


[1, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15, 16, 17]
[2, 10, 13, 18, 19, 20]
>>> 

以下是如何将其可视化

>>> import matplotlib.pyplot as plt
>>> nx.draw(G)
>>> plt.show()

enter image description here

答案 1 :(得分:2)

几点说明:

  1. 某些值是数字而某些值是列表并不方便。首先尝试将数字转换为单项列表。
  2. 如果订单不重要,最好使用set而不是列表。他们有各种“逻辑”操作的方法。
  3. 然后你可以这样做:

    In [1]: dict1 = {'1': {1, 3}, '2': {2}}
    
    In [2]: dict2 = {'1': {4}, '2': {10}, '3': {5, 9}}
    
    In [3]: dict3 = {'1': {6, 8, 11}, '2': {13}, '4': {12}}
    
    In [4]: {k: set.union(*(d[k] for d in (dict1, dict2, dict3)))
        for k in set.intersection(*(set(d.keys()) for d in (dict1, dict2, dict3)))}
    Out[4]: {'1': set([1, 3, 4, 6, 8, 11]), '2': set([2, 10, 13])}
    

答案 2 :(得分:2)

In [106]: level1dict = { '1':[1,3], '2':2 }

In [107]: level2dict = { '1':4, '3':[5,9], '2':10 }
In [108]: level3dict = { '1':[6,8,11], '4':12, '2':13, '3':[14,15], '5':16, '9':17, '10':[18,19,20]}

In [109]: keys=set(level2dict) & set(level1dict) & set(level3dict) #returns ['1','2']
In [110]: dic={}

In [111]: for key in keys:
    dic[key]=[]
    for x in (level1dict,level2dict,level3dict):
        if isinstance(x[key],int):
            dic[key].append(x[key])
        elif isinstance(x[key],list):
            dic[key].extend(x[key])
   .....:             

In [112]: dic
Out[112]: {'1': [1, 3, 4, 6, 8, 11], '2': [2, 10, 13]}

# now iterate over `dic` again to get the values related to the items present
# in the keys `'1'` and `'2'`.

In [122]: for x in dic:
    for y in dic[x]:
        for z in (level1dict,level2dict,level3dict):
            if str(y) in z and str(y) not in dic:
                if isinstance(z[str(y)],(int,str)):
                     dic[x].append(z[str(y)])
                elif isinstance(z[str(y)],list):
                     dic[x].extend(z[str(y)])
   .....:                     

In [123]: dic
Out[123]: 
{'1': [1, 3, 4, 6, 8, 11, 5, 9, 14, 15, 12, 16, 17],
 '2': [2, 10, 13, 18, 19, 20]}