首页 > 解决方案 > 将多个字典与相同的键组合起来,并附加它们的值

问题描述

我使用 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']}

标签: pythondictionary

解决方案


你可以使用一个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']})

推荐阅读