Python – Modifying a List of Dictionaries Using Map

Assume we have a list of python dictionaries, and all of the dictionaries have a common key, let’s call it ‘numeric_value’

list = [{'numeric_value' : 0}, {'numeric_value' : 3}, {'numeric_value' : 5}, {'numeric_value' : 2}]

Now, we want to add a field to each of the dictionaries, let’s call it ‘prime’. We want it to be True if ‘numeric_value’ is a prime number, and False otherwise.

Assume that we have already implemented a simple function ‘is_prime(number)’ which checks whether a number is prime or not.

The simple approach:

for idx,item in enumerate(list):
    list[idx]['Prime'] = is_prime(item['numeric_value'])

Which works, but it’s not attractive enough :D

This is how I implement it when I’m bored:

list = map(lambda x: dict(x.items() + [('prime', is_prime(x['numeric_value'])]), list)

Note: I’m NOT saying that you should do it this way :)

Leave a Reply