Skip to content Skip to sidebar Skip to footer

Python: DIvide Items Of A Dictionary By A Value That Depends On The First Key

I believe that this questions is very similar to Divide each python dictionary by total value, however I am not able to deal with multidimentional key. So I have this first diction

Solution 1:

Wrap i and j with an additional set of parentheses, since y.items() returns something of the form <(k1, k2), v>.

Some things to account for:

  1. Division by 0
  2. How to handle missing entries in x

{(i, j) : v / max(x.get(i, 1), 1) for (i, j), v in y.items()}

You can either choose to handle the division by 0, or let an exception be thrown. Additionally, if i is missing in x, you should think how you'd want to handle that. I've assumed nothing is done (i.e., division by 1).


Solution 2:

you can try:

{k: v / (x[k[0]] or 1) for k,v in y.items()}

where x[k[0]] or 1 fix ZeroDivisionError


Solution 3:

The error is due to the part i,j,v in y.items(). y.items() returns a enumerable collection of 2 item types of the form (<key>,<value>).
Since here your key is itself a tuple, you can unpack it further by wrapping the i,j in brackets so: (i,j),v in y.items() which will unpack the key item pair and then unpack the compound key.

Overall this gives: y = {[i,j]: v / (x[i]) for (i,j),v in y.items()}

You may also encounter the issue that the key cannot be a list, as lists cannot be hash, so you will have to substitute [i,j] for (i,j).


Solution 4:

You can try something like this

y = {k: v / (x[k[0]]) for k,v in y.items() if x[k[0]]}

Post a Comment for "Python: DIvide Items Of A Dictionary By A Value That Depends On The First Key"