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, 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With