4

I have got the below problem.

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Normal retrieval method: dict1['a'] -> Output - > 1
expected method: dict1['a', 'b'] - > Output - > [1, 2]

My requirement is to extract multiple values from a dictionary by providing multiple keys at the same time as mentioned in the expected method above.

Is there a way to do it? If I have to edit the built-in dict class methods, how do I do it?

ruohola
  • 21,987
  • 6
  • 62
  • 97
VISHBALA
  • 87
  • 1
  • 1
  • 5

4 Answers4

5

You can do what's said in the other answers or use map on your list of keys with the get dictionary method:

list(map(dict1.get, ["a", "b"]))
uzluisf
  • 2,586
  • 1
  • 9
  • 27
Nenri
  • 477
  • 3
  • 18
  • This answer return 'map object'. Must be enclose with 'list' for result to be 'list' ==> list(map(dict1.get, ["a", "b"])) – Erman Kadir Kahraman Jun 28 '23 at 10:10
  • @ErmanKadirKahraman If the need is just to iterate over it, keeping it as a map is good enough and even a better practice. I'd advice to convert to a list only if you specifically need a list – Nenri Jun 30 '23 at 13:05
4

Use a list comprehension:

[ dict[k] for k in ('a','b')]
[ dict[k] for k in my_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 ]
nigel222
  • 7,582
  • 1
  • 14
  • 22
1

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])
Louis Saglio
  • 1,120
  • 10
  • 20
0

This is one way of doing this through subclassing:

class CustomDict(dict):
    def __init__(self, dic):
        self.dic = dic

    def __getitem__(self, items):
        values = []
        for item in items:
            values.append(self.dic[item])
        return values if len(values) > 1 else 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.

ruohola
  • 21,987
  • 6
  • 62
  • 97