我有两个变量一个是字典列表另一个是平面字典
- 我们必须匹配字典列表"id">
- 当找到匹配时,更新字典名称键值列表
下面是参考
lst1 = [{"id":"01","name":"michel","age":"30"},{"id":"02","name":"oliever","age":"29"},{"id":"04","name":"james","age":"28"}] #list of dictionaries
lst2 = {"01":"Surendra","02":"Ravi","03":"Ramu"}#Dictionary
当我们打印(lst1)时,输出将如下所示
O/p:[{'id': '01', 'name': 'Surendra', 'age': '30'}, {'id': '02', 'name': 'Ravi', 'age': '29'}, {'id': '04', 'name': 'james', 'age': '28'}]
for l in lst1:
if l[ 'id' ] in lst2:
l[ 'name' ] = lst2[ l[ 'id' ] ]
else:
pass
lst1 = [
{"id": "01", "name": "michel", "age": "30"},
{"id": "04", "name": "oliever", "age": "29"},
{"id": "03", "name": "james", "age": "28"}
]
lst2 = {"01": "Surendra", "02": "Ravi", "03": "Ramu"}
for l in lst1:
if l['id'] in lst2:
l['name'] = lst2[l['id']]
print(lst1)
[{'id': '01', 'name': 'Surendra', 'age': '30'}, {'id': '04', 'name': 'oliever', 'age': '29'},{'id': '03', 'name': 'Ramu', 'age': '28'}]