0

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])

5 Answers 5

4

Use list expression checking key existence

result=[dictionary[k] for k in keys if k in dictionary]
Sign up to request clarification or add additional context in comments.

Comments

3

Use a list comprehension:

[dictionary[k] for k in keys]

Comments

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

Comments

1

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']

1 Comment

This print all values, Is there any difference with a simple dictionary.values()? What about knonw keys array?
0

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]

1 Comment

This is an inefficient implementation of dictionary.values() that does not limit the results to those for a known list of keys, as the OP requested.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.