In Python3 , How to update the dict using comprehensions

I have a List like this:

oldL = [
    {"id":1, "name":"aaa"},
    {"id":2, "name":"bbb"},
    {"id":3, "name":"ccc"},
]

and I want to convert to this:

newL = [
    {"id":1, "name":"aaa", "age":16},
    {"id":2, "name":"bbb", "age":16},
    {"id":3, "name":"ccc", "age":16}
]

By using “for structure” like this:

li = []
for sd in oldL:
    sd.update({"age":16})
    li.append(sd)
print(li)

I can get the right result, But I want to use the Comprehensions, How to get it? Thanks a lot.

I had test the case:

newL=[ sd.update({"age": 16}) for sd in oldL]

but I got [None, None, None], because the return value of update() is None.

If I test the case like this:

detailL =[ (sd.update({"age": 16}), sd) for sd in schedule_detailL]

the result is :

[(None, {'id': 1, 'name': 'aaa', 'schedule_id': 1}), (None, {'id': 2, 'name': 'bbb', 'schedule_id': 1}), (None, {'id': 3, 'name': 'ccc', 'schedule_id': 1})]

Answer

In Python 3 you can use the ** dictionary unpacking operator to unpack the original dictionary and then create a new one with the addition of the age key:

oldL = [
    {"id":1, "name":"aaa"},
    {"id":2, "name":"bbb"},
    {"id":3, "name":"ccc"},
]

newL = [ { **d, "age": 16 } for d in oldL ]
print(newL)

Output:

[
 {'id': 1, 'name': 'aaa', 'age': 16},
 {'id': 2, 'name': 'bbb', 'age': 16},
 {'id': 3, 'name': 'ccc', 'age': 16}
]

Note that this creates new dictionaries; it does not update the old ones. To update the old ones requires the use of update in a loop e.g.

for d in oldL:
    d.update({"age": 16})
print(oldL)

Output:

[
 {'id': 1, 'name': 'aaa', 'age': 16},
 {'id': 2, 'name': 'bbb', 'age': 16},
 {'id': 3, 'name': 'ccc', 'age': 16}
]