0

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?

mickeymoon
  • 4,820
  • 5
  • 31
  • 56
Subhayan Bhattacharya
  • 5,407
  • 7
  • 42
  • 60
  • Possible duplicate of [Rename a dictionary key](https://stackoverflow.com/questions/16475384/rename-a-dictionary-key) –  Jul 25 '19 at 11:17
  • 1
    it will be less readable with a list comprehension honestly – gold_cy Jul 25 '19 at 11:18
  • 1
    "But i am wondering if i can use the list comprehension method for doing this ?" — Yes you could, but why would you? Doing so would be very unideomatic. – L3viathan Jul 25 '19 at 11:18

2 Answers2

3

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}]
L3viathan
  • 26,748
  • 2
  • 58
  • 81
1

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)