简体   繁体   中英

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

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.

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, eg :

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]
>>> zip(my_list, operator.itemgetter(*my_list)(my_dictionary))
[(1, 'hello'), (2, 'goodbye'), (3, 'World')]

How about this? Take every item in my_list and pass it to the dictionary's get method. It also handles exceptions around missing keys by replacing them with None .

map(my_dictionary.get, my_list)

If you want tupples zip it -

zip(my_list, map(my_dictionary.get, my_list))

If you want a new dict, pass the tupple to dict.

dict(zip(my_list, map(my_dictionary.get, my_list)))

A straight forward way would be to pick each item from the dictionary and check if the key is present in the list

>>> [e for e in my_dictionary.items() if e[0] in my_list]
[(1, 'hello'), (2, 'goodbye'), (3, 'World')]

The above search would be linear so you might gain some performance by converting the list to set

>>> [e for e in my_dictionary.items() if e[0] in set(my_list)]
[(1, 'hello'), (2, 'goodbye'), (3, 'World')]

And finally if you need a dictionary instead of a list of key,value pair tuples you can use dictionary comprehension

>>> dict(e for e in my_dictionary.items() if e[0] in set(my_list))
{1: 'hello', 2: 'goodbye', 3: 'World'}
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM