Reputation: 19369
With dictionary:
dictionary={1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five'}
and a list of known keys:
keys=[2, 4]
What is the fastest shortest way to retrieve dictionary values?
The goal is to replace this code:
result=[]
for key in dictionary:
if not key in keys: continue
result.append(dictionary[key])
Upvotes: 0
Views: 94
Reputation: 5193
Use list expression checking key existence
result=[dictionary[k] for k in keys if k in dictionary]
Upvotes: 4
Reputation: 22697
EDITED you can use this
result = map(lambda x:x[1],dictionary.items())
Example
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]
Upvotes: 0
Reputation: 202
Try this,
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']
Upvotes: 1