Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to take an ordered "slice" of a dictionary in Python based on a list of keys?

Tags:

python

Suppose I have the following dictionary and list:

my_dictionary = {1:"hello", 2:"goodbye", 3:"World", "sand":"box"}
my_list = [1,2,3]

Is there a direct (Pythonic) way to get the key-value pairs out of the dictionary for which the keys are elements in the list, in an order defined by the list order?

The naive approach is simply to iterate over the list and pull out the values in the map one by one, but I wonder if python has the equivalent of list slicing for dictionaries.

like image 504
merlin2011 Avatar asked Mar 29 '12 19:03

merlin2011


1 Answers

Don't know if pythonic enough but this is working:

res = [(x, my_dictionary[x]) for x in my_list]

This is a list comprehension, but, if you need to iterate that list only once, you can also turn it into a generator expression, e.g. :

for el in ((x, my_dictionary[x]) for x in my_list):
    print el

Of course the previous methods work only if all elements in the list are present in the dictionary; to account for the key-not-present case you can do this:

res = [(x, my_dictionary[x]) for x in my_list if x in my_dictionary]
like image 181
digEmAll Avatar answered Oct 24 '22 06:10

digEmAll