Subhayan Bhattacharya
Subhayan Bhattacharya

Reputation: 5705

How to update a key in a list of dictionaries in Python

I have a very simple use case in which I have to update a key inside a list of dictionaries. The code goes like this:

original = [
    {
        "name": "Subhayan",
        "age": 34
    },
    {
        "name": "Poulomi",
        "age": 30
    }
]

update_data = {
    "Subhayan": 50,
    "Poulomi": 46
}

check = [x["age"] = update_data[x["name"]] for x in original]
print(check)

I have this strange error :

  File "try_defaultdict.py", line 17
    check = [x["age"] = update_data[x["name"]] for x in original]
                      ^
SyntaxError: invalid syntax

I know this can be done using a simple for loop. But I am wondering if I can use the list comprehension method for doing this?

Upvotes: 0

Views: 94

Answers (2)

Vignesh Bayari R.
Vignesh Bayari R.

Reputation: 663

Try this, this way, you can update the value in place:

 original = [
     {
         "name": "Subhayan",
         "age" : 34
     },
     {
         "name": "Poulomi",
         "age" : 30
     }
 ]

 update_data = {
     "Subhayan" : 50,
     "Poulomi"  : 46
 }

 [x.update({"age": update_data.get(x["name"])}) for x in original]
 print(original)

Upvotes: 1

L3viathan
L3viathan

Reputation: 27273

Maybe you want to create new dictionaries? In that case, this is possible and okay:

check = [{"name": x["name"], "age": update_data[x["name"]]} for x in original]

Result:

>>> check
[{'name': 'Subhayan', 'age': 50}, {'name': 'Poulomi', 'age': 46}]

Upvotes: 3

Related Questions