linkyndy
linkyndy

Reputation: 17900

Apply a function on a dict's items

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

Answers (4)

dano
dano

Reputation: 94891

This is a one-liner. Not sure I'd consider it "more pythonic", though

map(function, *zip(*d.iteritems()))

Upvotes: 3

sffjunkie
sffjunkie

Reputation: 52

[function(x, y) for x, y in d.items()]

Upvotes: 0

Veedrac
Veedrac

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

6502
6502

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

Related Questions