How To Extract Dictionary Values By Using Multiple Keys At The Same Time?
Solution 1:
Use a list comprehension:
[ dict[k]forkin ('a','b')]
[ dict[k]forkinmy_iterable ]
will throw KeyError if any of the keys in the iterable are not in the dict. It may be better to do
[ dict.get(k, my_default_value) for k in my_iterable ]
Solution 2:
You can use list comprehension : [dict1[key] for key in ('a', 'b')]
It is equivalent to
output = []
for key in ('a', 'b'):
output.append(dict1[key])
Solution 3:
You can do what's said in the other answers or use map
on your list of keys with the get
dictionnary method :
map(dict1.get, ["a", "b"])
Solution 4:
This is one way of doing this through subclassing:
classCustomDict(dict):
def__init__(self, dic):
self.dic = dic
def__getitem__(self, items):
values = []
for item in items:
values.append(self.dic[item])
return values iflen(values) > 1else values[0]
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
new_d = CustomDict(d)
print(new_d['a'])
print(new_d['a', 'b'])
print(new_d['a', 'b', 'c'])
print(new_d['a', 'c', 'd'])
Output:
1 [1, 2] [1, 2, 3] [1, 3, 4]
Explanation:
The new_d
is an object of the CustomDict
class, it will always fall back to the parent class's methods (so that looping over the object and other things you might want to do to a dictionary work) except when one of the overriden methods (init, getitem) get called.
So when one uses new_d['a', 'b']
the overriden __getitem__
method gets called. The overriden method uses the __getitem__
of the self.dic
(which is a normal dictionary) to actually access the dictionary values for every key given.
Post a Comment for "How To Extract Dictionary Values By Using Multiple Keys At The Same Time?"