简体   繁体   English

根据公共键合并字典列表

[英]Merge list of dictionaries based on common key

How to append a list of dictionaries value to another list.如何将 append 一个字典值列表赋给另一个列表。 This my first dict:这是我的第一个命令:

d=[{'title': 'a', 'num_iid': 36167009077, 'seller_id': 249772349},{'title': 'b', 'num_iid': 1234, 'seller_id': 249772349},{'title': 'c',  'num_iid': 12784, 'seller_id': 12475}]

and the list that I want to append it:以及我想要 append 的列表:

d1=[{'title': 'a', 'image_url': 'a.jpg', 'subtitle': '140.00', 'buttons': [{'type': 'postback', 'title': 'Details', 'payload': '/'}, {'type': 'postback', 'title': 'shop', 'payload': '/'}]}, {'title': 'b', 'image_url': 'b.jpg', 'subtitle': '2193.00', 'buttons': [{'type': 'postback', 'title': 'Details', 'payload': '/'}, {'type': 'postback', 'title': 'shop', 'payload': '/'}]}, {'title': 'c', 'image_url': 'c.jpg', 'subtitle': '3203.00', 'buttons': [{'type': 'postback', 'title': 'Details', 'payload': '/'}, {'type': 'postback', 'title': 'shop', 'payload': '/'}]}]

What I need is insert the 'num_iid' and 'seller_id' in each buttons payload我需要的是在每个按钮有效负载中插入“num_iid”和“seller_id”

Expected output:预计 output:

result=[{'title': 'a', 'image_url': 'a.jpg', 'subtitle': '140.00', 'buttons': [{'type': 'postback', 'title': 'Details', 'payload': '36167009077'}, {'type': 'postback', 'title': 'shop ', 'payload': '249772349'}]}, {'title': 'b', 'image_url': 'b.jpg', 'subtitle': '2193.00', 'buttons': [{'type': 'postback', 'title': 'Details', 'payload': '1234'}, {'type': 'postback', 'title': 'shop', 'payload': '249772349'}]}, {'title': 'c', 'image_url': 'c.jpg', 'subtitle': '3203.00', 'buttons': [{'type': 'postback', 'title': 'Details', 'payload': '12784'}, {'type': 'postback', 'title': 'shop', 'payload': '12475'}]}]

First:第一的:

num_iids = {item['title']: item.get('num_iid', '/') for item in d}
seller_ids = {item['title']: item.get('seller_id', '/') for item in d}

Then:然后:

for item in d1:
    title = item['title']
    item['buttons'][0]['payload'] = num_iids.get(title, '/')
    item['buttons'][1]['payload'] = seller_ids.get(title, '/')

Try this:尝试这个:

for d_find in d:
    for d1_find in d1:
        if d_find['title'] == d1_find['title']:
            d1_find['buttons'][0]['payload'] = d_find['num_iid']
            d1_find['buttons'][1]['payload'] = d_find['seller_id']
            
            break
        
print(d1)

You can do it with a for loop and enumerate() :您可以使用 for 循环和enumerate()来完成:

for i, j in enumerate(d1):
    j['buttons'][0]['payload'] = d[i]['num_iid']
    j['buttons'][1]['payload'] = d[i]['seller_id']

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

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