-3

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.

Aditya
  • 57
  • 1
  • 1
  • 6
  • 1
    What you did would have worked except you have bugs in that code. It is not efficient, though. You might consider OrderedDict with id as the key, sorted by rank. – Kenny Ostrom Aug 08 '19 at 19:04
  • 1
    Do you mean something like [this](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary)? You might also use the id as a key for the specific dictionaries. – csabinho Aug 08 '19 at 19:07
  • I tried values[val] and value[new][0] and the issue got resolved. The dictionary was replaced as an entire list which was the cause of the issue – Aditya Aug 08 '19 at 20:02

1 Answers1

1

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}]
nmpauls
  • 140
  • 1
  • 8