Reputation: 17900
Basically, I am looking for a way to rewrite the following in a simpler, more pythonic fashion:
for key, value in dictionary.items():
function(key, value)
Is there a way to achieve this?
Upvotes: 1
Views: 144
Reputation: 94891
This is a one-liner. Not sure I'd consider it "more pythonic", though
map(function, *zip(*d.iteritems()))
Upvotes: 3
Reputation: 60147
You can also do
from itertools import starmap
from collections import deque
exhaust_iterable = deque(maxlen=0).extend
exhaust_iterable(starmap(function, dictionary.items()))
if you really want to...
Upvotes: 2
Reputation: 114519
There's nothing much to factor out, but may be something that could be useful is
def dictmap(f, d):
return {k: f(k, v) for k, v in d.items()}
then you can write
result = dictmap(function, dictionary)
(given that keys are enumerated in a random order returning a list with the result doesn't make much sense and dictionary seems more appropriate).
Note however that for reasons that are not so clear to me map
and functional reasoning is sort of considered bad in the Python community (for example anonymous functions are second-class citizens and they got quite close to be completely removed from Python 3).
Upvotes: 1