vijayakumarpsg587
vijayakumarpsg587

Reputation: 1177

Dict list comprehension in Python

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?

Upvotes: 0

Views: 136

Answers (2)

Zionsof
Zionsof

Reputation: 1246

It's a bit complicated but here:

def list_mutate_dict(list1, mutable_func):
    [{key: (mutable_func(value) if key == 'age' else value) for key, value in item.items()} for item in list1]

Explanation (going inside out):

First, you mutate the value if needed in the condition inside the assignment, keeping all other values the same.
Then, you do this for all dictionary items by iterating all the items.
And, finally, you do this for all dictionaries in the list.

I will add a caveat that these types of list comprehensions are not considered a best practice and often lead to very confusing and unmaintainable code.

Upvotes: 1

Ronie Martinez
Ronie Martinez

Reputation: 1266

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.

Upvotes: 3

Related Questions