I'm trying to get a subset of values from a Python dictionary but I am wondering if there is a quick approach. Imagine that I have this:
my_dict = {'a':1, 'b':2, 'c':3}
and I want to get the values for both the a
and b
simultaneously as a list. I have tried the following methods and every one of them has raised an error.
my_dict['a', 'b'] # KeyError
my_dict[['a', 'b']] # TypeError (unhashable type: 'list')
my_dict[('a','b')] # KeyError
I have also tried the .get
method, but it didn't work either.
Now, I am aware that I can generate a list comprehension that gives me the answer:
subset = [my_dict[key] for key in ["a","b"]]
but I was wondering if there is an easier / shorter way of doing it. Passing a list of keys as an index to a dictionary and getting the corresponding list of values with dictionary[subset_of_keys] --> [subset_of_values]
would make sense.