0

Looking to gain some understanding on handling dictionaries efficiently in Python.

I have a dictionary

dict = {'a': 11, 'b': 4, 'c': 7, 'd': 12, 'e': 5}

and I would like to perform calculations only on a subset of its values. Which values to be considered in the calculations is based on their keys. Say, that these keys will be in a list of keys.

For example, if I would like to add the values of the keys a, b and e (i.e. keys_list_to_add=['a', 'b', 'e']) I would expect the result to be 20. Note, that several such subsets calculations may exist and a key may be missing (so, perhaps an exception should be raised in that case).

After seeing this answer, I tried to implement it with no success cause I am still learning Python. Could you please provide with code suggestions for my problem?

Community
  • 1
  • 1
  • Is it guaranteed that the "subset" of key is actually a subset? Would it be permissible for the answer to raise an exception if a key in the "subset" is not actually in your dictionary? – Rory Daulton Jun 11 '16 at 16:32
  • @RoryDaulton An exception should be raised if a key is missing, yes. (modified question) –  Jun 11 '16 at 16:44

1 Answers1

2

You can implement the given example with sum and generator expression that returns dict values based on keys:

>>> d = {'a': 11, 'b': 4, 'c': 7, 'd': 12, 'e': 5}
>>> keys_list_to_add = ['a', 'b', 'e']
>>> sum(d[k] for k in keys_list_to_add)
20

It raises KeyError in case that given key doesn't exists in the dict:

>>> keys_list_to_add = ['a', 'b', 'f']
>>> sum(d[k] for k in keys_list_to_add)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <genexpr>
KeyError: 'f'

If you want to handle the error in one way or another you could use try/except:

>>> try:
...     sum(d[k] for k in keys_list_to_add)
... except KeyError:
...     print 'Missing key'
...
Missing key

Or you could interpret missing key as 0:

>>> sum(d.get(k, 0) for k in keys_list_to_add)
15

Note that you shouldn't use build-in method names like dict for variables since that hides the method:

>>> dict(a=1)
{'a': 1}
>>> dict = {1:2}
>>> dict(a=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
niemmi
  • 17,113
  • 7
  • 35
  • 42
  • That is what I want, thanks. Could you please elaborate on how to handle the `keyerror`? I do not understand how at `try..except` or an `if k in keys_list_to_add` befor the `for` loop should be implemented. –  Jun 12 '16 at 08:30
  • @nk-fford I added couple options on how to handle the missing keys but since I don't know the context it's impossible to tell what's the "correct" way, – niemmi Jun 12 '16 at 15:41