首页 > 解决方案 > 将两个字典合并到Python中的字典字典中

问题描述

我有一个来自集合库的默认字典,它显示了图的每个节点的所有连接的列表:

edges = {1 : [987, 682, 465], 
         2 : [45, 67, 85, 907, ...],
         ...
         n : [32, 563, 659, 902]}

我还有另一个为每个节点存储它所属的类别,如下所示:

categories = {1 : ['category1', 'category37'], 
              2 : ['category45', 'category86', ...],
             ... , 
              n : ['category1','category2'], ....}

我想获得一个最终的字典,它为每个类别包含该类别的所有连接的字典,它看起来像这样:

final = {'category1' : {1 : [987, 682, 465], 37: [84, 777, 90, 744, 343], ...},
         'category2' : {37 : [84, 777, 90, 744, 343], 64: [32, 1222], ...}
          ...}

标签: pythonpython-3.xdictionarycollections

解决方案


您可以使用嵌套循环来完成此操作。

一行版本:

final = {category: {edge: edges[edge]} for edge in edges \
         for category in categories[edge] if category in categories[edge]}

详细版本,步骤清晰:

final = {}
for edge in edges:  # loop through each edge
    # find all categories that belong to the current edge in outer loop and then append 
    # the edge list to the corresponding category in the final dictionary
    for category in categories[edge]:
        if category in final:
            final[category][edge] = edges[edge]
        else:
            final[category] = {edge: edges[edge]}

为了测试这一点,我做了一个例子。

edges = {1:[11,56,3], 2:[69,4,5,6], 3:[1,8,96,5]}
categories = {1:['category1', 'category37'],2:['category45', 'category86'],3:['category1','category2']}

结果是

{'category1': {1: [11, 56, 3], 3: [1, 8, 96, 5]},
 'category37': {1: [11, 56, 3]},
 'category45': {2: [69, 4, 5, 6]},
 'category86': {2: [69, 4, 5, 6]},
 'category2': {3: [1, 8, 96, 5]}}

推荐阅读