Get elements from dict using multiple keys

后端 未结 2 416
我寻月下人不归
我寻月下人不归 2021-01-27 03:42

If I have:

d = {\'one\':1, \'two\':2, \'three\':3, \'four\':4}

How can I get values of \'one\' and \'three\' in one command. Something like thi

相关标签:
2条回答
  • 2021-01-27 04:04

    You can just directly access them:

    >>> d = {'one':1, 'two':2, 'three':3, 'four':4}
    >>> [d['one'], d['three']]
    [1, 3]
    >>> 
    

    In the method you use, it is searching for the key ('one', 'three') in d, which obviously doesn't exist.

    0 讨论(0)
  • 2021-01-27 04:19

    Using list comprehension:

    >>> d = {'one':1, 'two':2, 'three':3, 'four':4}
    >>> [d[key] for key in 'one', 'three']
    [1, 3]
    
    0 讨论(0)
提交回复
热议问题