Python字典获取多个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24204087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python dictionary get multiple values
提问by PKlumpp
Sry if this question already exists, but I've been searching for quite some time now.
Sry 如果这个问题已经存在,但我已经搜索了很长一段时间。
I have a dictionary in python, and what I want to do is get some values from it as a list, but I don't know if this is supported by the implementation.
我在python中有一个字典,我想做的是从中获取一些值作为列表,但我不知道实现是否支持。
myDictionary.get('firstKey') # works fine
myDictionary.get('firstKey','secondKey')
# gives me a KeyError -> OK, get is not defined for multiple keys
myDictionary['firstKey','secondKey'] # doesn't work either
But is there any way I can achieve this? In my example it looks easy, but let's say I have a dictionary of 20 entries, and I want to get 5 keys. Is there any other way than doing
但是有什么办法可以做到这一点吗?在我的示例中,它看起来很简单,但是假设我有一个包含 20 个条目的字典,并且我想要获得 5 个键。除了做还有什么办法
myDictionary.get('firstKey')
myDictionary.get('secondKey')
myDictionary.get('thirdKey')
myDictionary.get('fourthKey')
myDictionary.get('fifthKey')
采纳答案by ComputerFellow
Use a forloop:
使用for循环:
keys = ['firstKey', 'secondKey', 'thirdKey']
for key in keys:
myDictionary.get(key)
or a list comprehension:
或列表理解:
[myDictionary.get(key) for key in keys]
回答by Veedrac
There already exists a function for this:
已经存在一个函数:
from operator import itemgetter
my_dict = {x: x**2 for x in range(10)}
itemgetter(1, 3, 2, 5)(my_dict)
#>>> (1, 9, 4, 25)
itemgetterwill return a tuple if more than one argument is passed. To pass a list to itemgetter, use
itemgetter如果传递了多个参数,将返回一个元组。要将列表传递给itemgetter,请使用
itemgetter(*wanted_keys)(my_dict)
Keep in mind that itemgetterdoes not wrap its output in a tuple when only one key is requested, and does not support zero keys being requested.
请记住,itemgetter当仅请求一个键时,不会将其输出包装在元组中,并且不支持请求零键。
回答by bustawin
You can use Atfrom pydash:
您可以At从 pydash使用:
from pydash import at
dict = {'a': 1, 'b': 2, 'c': 3}
list = at(dict, 'a', 'b')
list == [1, 2]
回答by Mux
If the fallback keys are not too many you can do something like this
如果后备键不是太多,你可以做这样的事情
value = my_dict.get('first_key') or my_dict.get('second_key')
回答by CbeDroid1614
Use list comprehension and create a function:
使用列表理解并创建一个函数:
def myDict(**kwargs):
# add all of your keys here
keys = ['firstKey','secondKey','thirdKey','fourthKey']
# iterate through keys
# return the key element if it's in kwargs
list_comp = ''.join([val for val in keys if val in kwargs ])
results = kwargs.get(list_comp,None)
print(results)
回答by scottt
No-one has mentioned the mapfunction, which allows a function to operate element-wise on a list:
没有人提到过这个map函数,它允许函数在列表上按元素操作:
mydictionary = {'a': 'apple', 'b': 'bear', 'c': 'castle'}
keys = ['b', 'c']
values = list( map(mydictionary.get, keys) )
# values = ['bear', 'castle']
回答by Mosqueteiro
If you have pandasinstalled you can turn it into a series with the keys as the index. So something like
如果你已经pandas安装,你可以把它变成一个以键为索引的系列。所以像
import pandas as pd
s = pd.Series(my_dict)
s[['key1', 'key3', 'key2']]
回答by Epion
As I see no similar answer here - it is worth pointing out that with the usage of a (list / generator) comprehension, you can unpack those multiple values and assign them to multiple variables in a single line of code:
因为我在这里没有看到类似的答案 - 值得指出的是,通过使用(列表/生成器)理解,您可以解压缩这些多个值并将它们分配给一行代码中的多个变量:
first_val, second_val = (myDict.get(key) for key in [first_key, second_key])

