alphanumeric
alphanumeric

Reputation: 19369

How to get dictionary values having its keys as a list

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

Answers (5)

xecgr
xecgr

Reputation: 5193

Use list expression checking key existence

result=[dictionary[k] for k in keys if k in dictionary]

Upvotes: 4

levi
levi

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

drawde83
drawde83

Reputation: 139

print [dictionary[k] for k in dictionary.keys() if k in keys]

Upvotes: 2

Sesha
Sesha

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

BrenBarn
BrenBarn

Reputation: 251568

Use a list comprehension:

[dictionary[k] for k in keys]

Upvotes: 3

Related Questions