How to get multiple dictionary values?
Sorry if this question already exists, but I've been searching for quite some time now.
I have a dictionary in python, and what I want to do is get some values from it as a list, but I don't know if this is supported by the implementation.
myDictionary.get('firstKey') # works fine
myDictionary.get('firstKey','secondKey')
# gives me a KeyError -> OK, get is not defined for multiple keys
myDictionary['firstKey','secondKey'] # doesn't work either
But is there any way I can achieve this? In my example it looks easy, but let's say I have a dictionary of 20 entries, and I want to get 5 keys. Is there any other way than doing
myDictionary.get('firstKey')
myDictionary.get('secondKey')
myDictionary.get('thirdKey')
myDictionary.get('fourthKey')
myDictionary.get('fifthKey')
Solution 1:
There already exists a function for this:
from operator import itemgetter
my_dict = {x: x**2 for x in range(10)}
itemgetter(1, 3, 2, 5)(my_dict)
#>>> (1, 9, 4, 25)
itemgetter
will return a tuple if more than one argument is passed. To pass a list to itemgetter
, use
itemgetter(*wanted_keys)(my_dict)
Keep in mind that itemgetter
does not wrap its output in a tuple when only one key is requested, and does not support zero keys being requested.
Solution 2:
Use a for
loop:
keys = ['firstKey', 'secondKey', 'thirdKey']
for key in keys:
myDictionary.get(key)
or a list comprehension:
[myDictionary.get(key) for key in keys]
Solution 3:
I'd suggest the very useful map
function, which allows a function to operate element-wise on a list:
mydictionary = {'a': 'apple', 'b': 'bear', 'c': 'castle'}
keys = ['b', 'c']
values = list( map(mydictionary.get, keys) )
# values = ['bear', 'castle']
Solution 4:
You can use At
from pydash:
from pydash import at
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_list = at(my_dict, 'a', 'b')
my_list == [1, 2]
Solution 5:
As I see no similar answer here - it is worth pointing out that with the usage of a (list / generator) comprehension, you can unpack those multiple values and assign them to multiple variables in a single line of code:
first_val, second_val = (myDict.get(key) for key in [first_key, second_key])