python - 将多个字典与相同的键组合起来,并附加它们的值
问题描述
我使用 Python 3.9。我需要将多个字典与列表值合并到将数组值附加到每个键
{'xx5.8.38': ['testingxyz-597247']}
{'xx5.8.38': ['testingxyz-597624']}
{'xx5.8.38': ['testingxyz-597626']}
{'xx1.0.3': ['testingxyz-597247']}
{'xx1.0.3': ['testingxyz-597624']}
{'xx1.0.3': ['testingxyz-597626']}
(several more dicts)
结果应该是:
{'xx5.8.38': ['testingxyz-597247', 'testingxyz-597624', 'testingxyz-597626']}
{'xx1.0.3': ['testingxyz-597247', 'testingxyz-597624', 'testingxyz-597626']}
解决方案
你可以使用一个collections.defaultdict
from collections import defaultdict
input_dirs = [{'xx5.8.38': ['testingxyz-597247']},
{'xx5.8.38': ['testingxyz-597624']},
{'xx5.8.38': ['testingxyz-597626']},
{'xx1.0.3': ['testingxyz-597247']},
{'xx1.0.3': ['testingxyz-597624']},
{'xx1.0.3': ['testingxyz-597626']}]
result_dir = defaultdict(list)
for single_dir in input_dirs:
for key, val in single_dir.items():
result_dir[key].extend(val)
给你
defaultdict(<class 'list'>,
{'xx1.0.3': ['testingxyz-597247',
'testingxyz-597624',
'testingxyz-597626'],
'xx5.8.38': ['testingxyz-597247',
'testingxyz-597624',
'testingxyz-597626']})
推荐阅读
- html - Png变成意想不到的字符串
- php - m-Pesa STKPush 请求抛出错误“更新失败9”
- java - 如何通过移动电话进行更改
- python - self.driver.set_network_connection(1) 不适用于 selenium-python-client 的 android OS 版本 8
- python - 如何添加 matplotlib 轴单元
- node.js - pm2 中 GET 的可疑问题
- angular - 将查询字符串附加到 Angular 中的页面 url(没有 JQUERY)
- firebase - AngularFire(angular 8)存储——上传文档
- laravel - 如何在 Laravel 的 http\controller 中从供应商访问控制器?
- php - 为什么不显示插入数据,只显示更新数据?