映射字典查找

时间:2019-11-28 12:51:18

标签: python

我具有从字典中获取项目的功能:

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

我将通过多重处理将此功能映射为从一系列非常长字典中查找值:

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

我觉得我不必定义一个函数来从字典中获取值。有一些内置的方法可以做到这一点吗?

2 个答案:

答案 0 :(得分:4)

标准库的itemgetter模块中的operator函数提供了以下功能:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour {
    public void System()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex +1);
    }
    public void Back()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex -1);
    }
    public void Exit()
    {
        Debug.Log("You have exited the app");
        Application.Quit();
    }
}

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

>>> 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)] mapfilter的内置行为的函数的第一位。

答案 1 :(得分:1)

base_tr函数。每当您通过方括号dict.__getitem__来访问字典值时都会调用它,但是您可以显式调用它。

dictionary[key]