Skip to main content
 首页 » 编程设计

python之使用多个键从字典中获取元素

2025年05月04日14zengkefu

如果我有:

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

如何在一个命令中获取“一”和“三”的值。像这样:

out = d['one', 'three'] # But it gives an error 

请您参考如下方法:

使用 list comprehension :

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