Map dict lookup

The itemgetter function from the standard library's operator module provides this behaviour:

>>> import multiprocessing as mp
>>> import operator
>>> dictlist = [{'a': 1, 'b':2, 'c': 10}, {'a': 3, 'b': 4, 'c': 20},
                {'a': 5, 'b': 6, 'c': 30}]
>>> agetter = operator.itemgetter('a')
>>> with mp.Pool() as pool:
...     avalues = pool.map(agetter, dictlist)
... 
>>> avalues
[1, 3, 5]

It can also be used to retrieve values for multiple keys:

>>> bcgetter = operator.itemgetter('b', 'c')
>>> with mp.Pool() as pool:
...     bcvalues = pool.map(bcgetter, dictlist)
... 
>>> bcvalues
[(2, 10), (4, 20), (6, 30)]

In general, the operator module is the first place to look for a function that replicates a builtin's behaviour for use in map, filter or reduce.

Tags:

Python