Python字典获得多个值

发布于 2021-01-29 15:10:02

抱歉,这个问题已经存在,但是我已经搜索了很长时间。

我在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')
关注者
0
被浏览
61
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    使用for循环:

    keys = ['firstKey', 'secondKey', 'thirdKey']
    for key in keys:
        myDictionary.get(key)
    

    或列表理解:

    [myDictionary.get(key) for key in keys]
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看