简体   繁体   English

Python 合并多个字典

[英]Python Merging multiple dictionaries

I have a list as follows我有一个清单如下

 items = [{'Item Shortname': 'tshirt', 'Skins': '10053'},
 {'Item Shortname': 'tshirt', 'Skins': '10039'},
 {'Item Shortname': 'tshirt', 'Skins': '584379'},
 {'Item Shortname': 'tshirt', 'Skins': '10043'},
 {'Item Shortname': 'vending.machine', 'Skins': '861029759'},
 {'Item Shortname': 'vending.machine', 'Skins': '862137836'},
 {'Item Shortname': 'vending.machine', 'Skins': '869474635'},
 {'Item Shortname': 'water.purifier', 'Skins': '886677071'},
 {'Item Shortname': 'water.purifier', 'Skins': '786826476'}]

How do I generate an output like this:如何像这样生成 output:

{
  {'Item Shortname': 'tshirt', 'Skins': [0, 10053, 10039, 584379, 10043]},
  {'Item Shortname': 'vending.machine', 'Skins': [0, 861029759, 862137836, 869474635]},
  {'Item Shortname': 'water.purifier', 'Skins': [0, 886677071, 786826476]}
}

I have tried this with the default dict https://docs.python.org/3/library/collections.html#collections.defaultdict but couldn't figured out.我已经使用默认字典https://docs.python.org/3/library/collections.html#collections.defaultdict尝试过这个,但无法弄清楚。

Use a list instead of a dictionary for the final result.使用列表而不是字典来获得最终结果。 Then you can iterate over the initial items list and build the result iteratively.然后您可以迭代初始items列表并迭代构建结果。

summary = []

for item in items:
    name = item['Item Shortname']
    added = False
    # try to find a subnet with given address
    for elem in summary:
        if elem['Item Shortname'] == name:
            # if found, add domain to list
            elem['Skins'].append(int(item['Skins']))
            # and remember that we found a matching subnet
            added = True
            break
    if not added:
        # if we didn't find any subnet, add a new one
        summary.append({'Item Shortname': name,
                        'Skins': [ 0, int(item['Skins']) ] })

You can easily do it with the default dict, but you need an intermediate step, when you use the ItemShortname as key您可以使用默认字典轻松完成此操作,但是当您使用 ItemShortname 作为键时,您需要一个中间步骤

result = collections.defaultdict(list)
for item in items:
    result[item['Item Shortname']].append(int(item['Skins']))
print(result)  # {"tshirt": ["10053", "10039", "584379", "10043"], "vending.machine": ["861029759", "862137836", "869474635"], "water.purifier": ["886677071", "786826476"]}

result = [{'Item Shortname': k, 'Skins': v} for k, v in result.items()]
print(result)  # [{'Item Shortname': 'tshirt', 'Skins': [10053, 10039, 584379, 10043]}, {'Item Shortname': 'vending.machine', 'Skins': [861029759, 862137836, 869474635]}, {'Item Shortname': 'water.purifier', 'Skins': [886677071, 786826476]}]

Other way doing mostly the same but with groupby其他方式大致相同,但使用groupby

values = [list(item.values()) for item in items]
result = groupby(values, lambda x: x[0]) # from itertools import groupby
result = [{'Item Shortname': k, 'Skins': [int(x[1]) for x in v]} for k, v in result]

Giving the给予

[
    {
        "Item Shortname": "tshirt",
        "Skins": [10053,10039,584379,10043]
    },
    {
        "Item Shortname": "vending.machine",
        "Skins": [861029759,862137836,869474635]
    },
    {
        "Item Shortname": "water.purifier",
        "Skins": [886677071,786826476]
    }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM