简体   繁体   English

如何按键合并两个字典列表?

[英]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:我正在寻找的最终 output 是:

[{'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?我知道我可以使用几个循环来做到这一点,但有没有更好的 Pythonic 方式来做到这一点?

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 Output

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

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

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