Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53606

How to map a function to each dictionary element?

I have a dictionary self.what_to_build
I am iterating on each element, and apply another method to each element using the following way:

[self.typeBuild(obj_type,dest) for obj_type,dest in self.what_to_build.items()]

It is my understanding this builds a list in memory, while there is no real impact on the program, I would like to refrain from this, I really do not need the list, just applying the method. How would I do this same map, in the most Pythonic way, without doing a list comprehension

Upvotes: 0

Views: 60

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124928

Just use a regular loop:

for obj_type,dest in self.what_to_build.items():
    self.typeBuild(obj_type, dest)

A list comprehension indeed creates a list object with the return values of the self.typeBuild() calls, which is a waste of CPU and memory if you don't need those return values.

Don't get too hung up trying to write 'compact' code; readability is found in just the right level of verbosity.

Upvotes: 7

Related Questions