gpt4 book ai didi

python - 如何获取多个字典值?

转载 作者:IT老高 更新时间:2023-10-28 22:16:40 25 4
gpt4 key购买 nike

我在 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

有什么方法可以实现吗?在我的示例中,它看起来很简单,但假设我有一个包含 20 个条目的字典,并且我想获得 5 个键。除了做下面还有什么办法吗?

myDictionary.get('firstKey')
myDictionary.get('secondKey')
myDictionary.get('thirdKey')
myDictionary.get('fourthKey')
myDictionary.get('fifthKey')

最佳答案

已经存在一个函数:

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)
如果传递了多个参数,

itemgetter 将返回一个元组。要将列表传递给 itemgetter,请使用

itemgetter(*wanted_keys)(my_dict)

请记住,itemgetter 在仅请求一个键时不会将其输出包装在元组中,并且不支持请求零键。

关于python - 如何获取多个字典值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24204087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com