地图字典查询

2024-04-26 09:51:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从dict获取项目的函数:

def dict_lookup(dictionary, key):
    return dictionary[key]

我将通过多重处理映射此函数,从一系列非常长的dict中查找值:

dictlist = [{}, {}, {}]
dict_lookup_partial = functools.partial(dict_lookup, key=some_key)
with multiprocessing.Pool() as pool:
    values = pool.map(dict_lookup_partial, dictlist)

我觉得我不应该定义一个函数来从dict获取一个值。有没有一些内在的方法来做到这一点?你知道吗


Tags: 项目key函数dictionaryreturndefwithsome
2条回答

dict.__getitem__函数。每次通过方括号访问字典值时都会调用它,例如:dictionary[key],但是可以显式调用它。你知道吗

>>> d = {"foo": "bar"}
>>> dict.__getitem__(d, "foo")
"bar"

标准库operator模块中的itemgetter函数提供以下行为:

>>> 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]

它还可用于检索多个键的值:

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

一般来说,操作符模块是第一个查找复制内置函数行为的函数的地方,以便在mapfilterreduce中使用。你知道吗

相关问题 更多 >