简体   繁体   English

字典列表 - 如何合并字典列表 Python

[英]List of Dictionary - How to combine a list of dictionary Python

a =[{
    "id":"1",
    "Name":'BK',
    "Age":'56'
},
{
    "id":"1",
    "Sex":'Male'
},
{
    "id":"2",
    "Name":"AK",
    "Age":"32"
}]

I have a list of dictionary with a person information split in multiple dictionary as above for ex above id 1's information is contained in first 2 dictionary, how can i get an output of below我有一个字典列表,上面有一个人的信息被分成多个字典,因为上面的 id 1 的信息包含在第一个 2 字典中,我怎样才能得到下面的 output

{1: {'Name':'BK','Age':'56','Sex':'Male'}, 2: { 'Name': 'AK','Age':'32'}}

Using defaultdict使用defaultdict

from collections import defaultdict

a = [{
    "id": "1",
    "Name": 'BK',
    "Age": '56'
},
    {
        "id": "1",
        "Sex": 'Male'
    },
    {
        "id": "2",
        "Name": "AK",
        "Age": "32"
    }
]

final_ = defaultdict(dict)
for row in a:
    final_[row.pop('id')].update(row)

print(final_)

defaultdict(<class 'dict'>, {'1': {'Name': 'BK', 'Age': '56', 'Sex': 'Male'}, '2': {'Name': 'AK', 'Age': '32'}})

You can use a defaultdict to collect the results.您可以使用 defaultdict 来收集结果。

from collections import defaultdict

a =[{ "id":"1", "Name":'BK', "Age":'56' }, { "id":"1", "Sex":'Male' }, { "id":"2", "Name":"AK", "Age":"32" }]

results = defaultdict(dict)
key = lambda d: d['id']

for a_dict in a:
    results[a_dict.pop('id')].update(a_dict)

This gives you:这给你:

>>> results
defaultdict(<class 'dict'>, {'1': {'Name': 'BK', 'Age': '56', 'Sex': 'Male'}, '2': {'Name': 'AK', 'Age': '32'}})

The defaultdict type behaves like a normal dict, except that when you reference an unknown value, a default value is returned. defaultdict 类型的行为类似于普通的字典,只是当您引用未知值时,会返回默认值。 This means that as the dicts in a are iterated over, the values (except for id ) are updated onto either an existing dict, or an automatic newly created one.这意味着随着a中的字典被迭代,值(除了id )被更新到现有字典或自动新创建的字典中。

How does collections.defaultdict work? collections.defaultdict 是如何工作的?

from collections import defaultdict result = defaultdict(dict) a =[{ "id":"1", "Name":'BK', "Age":'56' }, { "id":"1", "Sex":'Male' }, { "id":"2", "Name":"AK", "Age":"32" }] for b in a: result[b['id']].update(b) print(result)

You can combine 2 dictionaries by using the.update() function您可以使用 the.update() function 合并 2 个词典

dict_a = { "id":"1", "Name":'BK', "Age":'56' }
dict_b = { "id":"1", "Sex":'Male' }
dict_a.update(dict_b) # {'Age': '56', 'Name': 'BK', 'Sex': 'Male', 'id': '1'}

Since the output the you want is in dictionary form因为你要的output是字典形式

combined_dict = {}

for item in a:
  id = item.pop("id")  # pop() remove the id key from item and return the value
  
  if id in combined_dict:
    combined_dict[id].update(item)
  else:
    combined_dict[id] = item

print(combined_dict)  # {'1': {'Name': 'BK', 'Age': '56', 'Sex': 'Male'}, '2': {'Name': 'AK', 'Age': '32'}}
d = {}
for p in a:
    id = p["id"]
    if id not in d.keys():
        d[id] = p
    else:
        d[id] = {**d[id], **p}

d is the result dictionary you want. d是你想要的结果字典。

In the for loop, if you encounter an id for the first time, you just store the incomplete value.在for循环中,如果第一次遇到id,就把不完整的值存进去。

If the id is in the existing keys, update it.如果 id 在现有密钥中,请更新它。

The combination happens in {**d[id], **p}组合发生在{**d[id], **p}

where ** is unpacking the dict.其中**解压字典。

It unpacks the existing incomplete dict associated withe the id and the current dict, then combine them into a new dict.它解压缩与 id 和当前字典关联的现有不完整字典,然后将它们组合成一个新字典。

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

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