[英]update an entire dictionary in a list of dictionaries based on key value pair
I have a list of dictionaries and I have to update an entire dictionary based on a specific key-value pair我有一个字典列表,我必须根据特定的键值对更新整个字典
values = [
{
"value" : "AAA",
"rank" : 10,
"id" : 1
},
{
"value" : "BBB",
"rank" : 50,
"id" : 2
}
]
I will receive a new list value_new = [{"value" : "CCC","rank" : 20,"id" : 1}]
.我将收到一个新列表
value_new = [{"value" : "CCC","rank" : 20,"id" : 1}]
。 The idea is to match the id and update the entire dictionary related to that id and sort the entire values list based on rank.这个想法是匹配 id 并更新与该 id 相关的整个字典,并根据排名对整个值列表进行排序。
I iterated through values list and matched based on id and when I tried to update it replaced the entire value list我遍历值列表并根据 id 进行匹配,当我尝试更新它时,它替换了整个值列表
I tried this piece of code我试过这段代码
for val in range(len(values)):
if values[val]['id'] == value_new['id']:
values[val] = value_new
I am unable to sort it after appending.添加后我无法对其进行排序。
I attempted to replicate what you want to do with this code:我试图用这段代码复制你想做什么:
values = [
{
"value" : "AAA",
"rank" : 10,
"id" : 1
},
{
"value" : "BBB",
"rank" : 50,
"id" : 2
}
]
print(values)
value_new = [{
"value" : "CCC",
"rank" :20,
"id" : 1
}]
# code for editing here
for val in values:
if value_new[0]['id'] == val['id']:
for key in value_new[0]:
val[key] = value_new[0][key]
print(values)
This changed the dictionary as you described:这如您所描述的那样更改了字典:
Before:前:
[{"value" : "AAA", "rank" : 10, "id" : 1}, {"value" : "BBB", "rank" : 50, "id" : 2}]
After:后:
[{"value" : "CCC", "rank" : 20, "id" : 1}, {"value" : "BBB", "rank" : 50, "id" : 2}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.