I am a python newbie. I am trying to learn comprehension and I am stuck currently with the scenario. I am able to do this mutation
sample_dict_list = [{'name': 'Vijay', 'age':30, 'empId': 1}, {'name': 'VV', 'age': 10, 'empId': 2},
{'name': 'VV1', 'age': 40, 'empId': 3}, {'name': 'VV2', 'age': 20, 'empId': 4}]
def list_mutate_dict(list1, mutable_func):
for items in list1:
for key,value in items.items():
if(key == 'age'):
items[key] = mutable_func(value)
return
mutable_list_func = lambda data: data*10
list_mutate_dict(sample_dict_list, mutable_list_func)
print(sample_dict_list)
[{'name': 'Vijay', 'age': 300, 'empId': 1}, {'name': 'VV', 'age': 100, 'empId': 2}, {'name': 'VV1', 'age': 400, 'empId': 3}, {'name': 'VV2', 'age': 200, 'empId': 4}]
Dict with key 'age' alone is mutated and returned
THis works fine. But I am trying the same with the single line comprehension. I am unsure if it can be done.
print([item for key,value in item.items() if (key == 'age') mutable_list_func(value) for item in sample_dict_list])
THis is the op - [{'age': 200}, {'age': 200}, {'age': 200}, {'age': 200}] which is incorrect. It just takes in the last value and mutates and returns as a dict list
Could this be done in a "nested" list dict comprehension?
When using comprehensions, you are actually creating a new one so "mutating" falls outside the context. But assuming you want the same output:
mutable_func = lambda data: data*10
print([{**d, "age": mutable_func(d["age"])} for d in sample_dict_list])
In my example you are unpacking the dictionary with **d
and adding another key-value which overwrites the existing one in d
.