简体   繁体   中英

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}] . 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.

I iterated through values list and matched based on id and when I tried to update it replaced the entire value list

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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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