Python字典获得多个值 [英] Python dictionary get multiple values
本文介绍了Python字典获得多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对不起,如果这个问题已经存在,但是我已经搜索了一段时间了。
Sry if this question already exists, but I've been searching for quite some time now.
我在python中有一个字典,我想做什么是从列表中获取一些值,但我不知道实现是否支持此操作。
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.
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个键。除了做
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
myDictionary.get('firstKey')
myDictionary.get('secondKey')
myDictionary.get('thirdKey')
myDictionary.get('fourthKey')
myDictionary.get('fifthKey')
推荐答案
使用进行
循环:
keys = ['firstKey', 'secondKey', 'thirdKey']
for key in keys:
myDictionary.get(key)
或列表理解:
[myDictionary.get(key) for key in keys]
这篇关于Python字典获得多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文