user6167676
user6167676

Reputation:

Performing calculations on some values in a dictionary based on their keys (Python)

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?

Upvotes: 0

Views: 11941

Answers (1)

niemmi
niemmi

Reputation: 17263

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

Upvotes: 2

Related Questions