简体   繁体   中英

How to merge two list of dicts by key?

I have the following two lists of dictionaries:

[{'cg_id': 'bitcoin', 'symbol': 'btc'}, {'cg_id': 'ethereum', 'symbol': 'eth'}]
[{'cmc_id': '1', 'symbol': 'btc'}, {'cmc_id': '1027', 'symbol': 'eth'}]

The final output I am looking for is:

[{'symbol': 'btc', 'cg_id': 'bitcoin','cmc_id': '1' },{'symbol':'eth','cg_id': 'ethereum','cmc_id': '1'} ]

I know I could use a few loops to do it but is there a better and pythonic way to do it?

d1 = [{'cg_id': 'bitcoin', 'symbol': 'btc'}, {'cg_id': 'ethereum', 'symbol': 'eth'}]
d2 = [{'cmc_id': '1', 'symbol': 'btc'}, {'cmc_id': '1027', 'symbol': 'eth'}]

d11 = {x["symbol"]: x for x in d1}
d22 = {x["symbol"]: x for x in d2}

for k in d22.keys():
    if k in d11:
        d11[k].update(d22[k])
list(d11.values())
# [{'cg_id': 'bitcoin', 'symbol': 'btc', 'cmc_id': '1'},
#  {'cg_id': 'ethereum', 'symbol': 'eth', 'cmc_id': '1027'}]

Using list comprehension.

l1  = [{'cg_id': 'bitcoin', 'symbol': 'btc'}, {'cg_id': 'ethereum', 'symbol': 'eth'}]
l2 = [{'cmc_id': '1', 'symbol': 'btc'}, {'cmc_id': '1027', 'symbol': 'eth'}]

merge = [{**l1[i], **l2[i]} for i in range(len(l1))]
print(merge)

Output

[{'cg_id': 'bitcoin', 'symbol': 'btc', 'cmc_id': '1'}, {'cg_id': 'ethereum', 'symbol': 'eth', 'cmc_id': '1027'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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