Python 如何获取键为列表的字典值

Python 如何获取键为列表的字典值,python,Python,使用字典: dictionary={1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five'} 以及已知密钥的列表: keys=[2, 4] 检索字典值的最快方法是什么 目标是替换此代码: result=[] for key in dictionary: if not key in keys: continue result.append(dictionary[key]) 已编辑您可以使用此 result = map(lambda

使用字典:

dictionary={1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five'}
以及已知密钥的列表:

keys=[2, 4]
检索字典值的最快方法是什么

目标是替换此代码:

result=[]
for key in dictionary:
    if not key in keys: continue
    result.append(dictionary[key])

已编辑您可以使用此

   result = map(lambda x:x[1],dictionary.items())
范例

   dictionary = {'x': 1, 'y': 2, 'z': 3} 
   dictionary.items()
   >>[('y', 2), ('x', 1), ('z', 3)]

   result = map(lambda x:x[1],dictionary.items())
   print result 
   >>[2, 1, 3]

使用列表理解:

[dictionary[k] for k in keys]

使用列表表达式检查键是否存在

result=[dictionary[k] for k in keys if k in dictionary]
试试这个

dictionary={1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five'}
result = [dictionary[i] for i in dictionary.keys()]
print result

Output:
['One', 'Two', 'Three', 'Four', 'Five']

这将打印所有值,与简单的字典有什么区别吗。values()?KNOW keys数组呢?这是
dictionary.values()
的一个低效实现,它没有按照OP的请求将结果限制为已知键列表的结果。
print [dictionary[k] for k in dictionary.keys() if k in keys]