python - 将两个字典合并到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], ...}
...}
解决方案
您可以使用嵌套循环来完成此操作。
一行版本:
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]}}
推荐阅读
- java - Java:通过自省、递归和注解进行依赖注入
- android - 约束布局:Textview 文本重叠按钮
- java - 异或运算符可以在java中添加或减去两个操作数吗?
- javascript - 如何使用 Selenium 和 Python 将文本插入 div 节点
- mongodb - 带 OR 条件的 mongo 查询说明
- c++ - 可以在 CUDA 速度计算中实现 Tensorflow 自定义操作梯度吗?
- java - 不在 java.net.URL 中使用 ">="
- angular - 在输入点击时为日期选择器创建指令
- python - Pil/Pillow 不支持 PNG 文件 - Kivy Buildozer
- c# - 实体框架核心——“如果不存在则插入”可能吗?