[英]Update list of dicts with keys/values from another list of dicts
Assume two list of dicts: 假设有两个字典列表:
leads and customers where len(customers) < len(leads): len(客户)<len(潜在客户):
customers = [{'name': 'Joe', 'age': 28}, {'name': 'Adam', 'age': 34}]
leads = [{'name': 'Joe', 'city': 'NYC'}, {'name': 'Molly', 'city': 'LA'},
{'name': 'Adam', 'city': 'Washington DC'}]
I need to update the customers dict with additional information from leads is the names match: 我需要使用潜在客户的其他信息来更新客户字典,因为名称匹配:
Desired output: 所需的输出:
output = [{'name': 'Joe', 'age': 28, 'city':'NYC'}, {'name': 'Adam', 'age': 34, 'city': 'Washington DC'}]
I've tried zip() and then looping through to match keys, but since they are lists, I'm getting a "list indices must be integers, not str" error 我试过zip(),然后遍历以匹配键,但是由于它们是列表,因此出现“列表索引必须是整数,而不是str”错误
You can create a dict using leads
list in which the data is stored against the name
and later use the name to update the data in customers
list. 您可以使用销售leads
列表创建字典,在其中根据name
存储数据,然后使用名称更新customers
列表中的数据。
>>> leads_data = {}
>>> for lead in leads:
... leads_data.setdefault(lead['name'], {}).update(lead)
...
>>> for c in customers:
... c.update(leads_data.get(c['name'], {}))
...
>>> customers
[{'city': 'NYC', 'age': 28, 'name': 'Joe'},
{'city': 'Washington DC', 'age': 34, 'name': 'Adam'}]
Here is my call on this: 这是我的要求:
for d in customers:
lead = [x for x in leads if x['name'] == d['name']]
if lead:
d.update(lead[0])
print(customers)
>>>
[{'city': 'NYC', 'age': 28, 'name': 'Joe'}, {'city': 'Washington DC', 'age': 34, 'name': 'Adam'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.