How to append a list of dictionaries value to another list. 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:
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
Expected 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'}]}]
CodePudding user response:
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)
CodePudding user response:
You can do it with a for loop and enumerate()
:
for i, j in enumerate(d1):
j['buttons'][0]['payload'] = d[i]['num_iid']
j['buttons'][1]['payload'] = d[i]['seller_id']
CodePudding user response:
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, '/')