python - 展开字典的快捷方式

标签 python dictionary

比如说,我有一个数据字典和它们的变量名,例如

dct = {'a': 1, 'b': 2, 'c':3}

我想检索与键子集关联的值。如何在不编写太多代码的情况下做到这一点,即一个一个地提取变量?有没有类似的东西

a, c = dct['a','c']

最佳答案

您可以为此使用生成器表达式:

>>> d = {'a':1,'b':2,'c':3}
>>> a, c = (d[key] for key in ['a', 'c'])
>>> a
1
>>> c
3

如果你这样做的次数足够多,值得用一个函数来包装,那是微不足道的:

>>> def multiget(mapping, *keys):
...     return (d[key] for key in keys)
>>> a, c = multiget(d, 'a', 'c')

但是,如果仔细观察,您会发现 multiget 只是 operator.itemgetter uncurried,使用它通常要简单得多:

>>> a, c = operator.itemgetter('a', 'c')(d)

关于python - 展开字典的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16993408/

相关文章:

python - 列表中包含的元组和字典

c++ - 为什么 std::map find() 没有声明为 noexcept?

python - 如何在 Python 中使用 Win32 API?

python - 把字典分成两半?

python - 在字典列表中搜索的最有效方法

python - 如何用一行代码在 Swift 2.0 中读取文本文件

python - 类型错误:从字典中提取值时字符串索引必须是整数

python - 用户模型字段未显示在 Django 管理面板中

python - (IntelliJ IDEA) "invalid Python interpreter selected for the module"

python - 逻辑: In a 2D data find and remove duplicates and average the y axis results