I have a dictionary where the key is a tuple. Some of these tuples are permutations of each other (e.g. (1, 2) vs (2, 1)). I want to add the value of one permutation to the other, and then get rid of the second permutation.
d = {(1, 3): 14, (1, 4): 13, (1, 2): 10, (11, 11): 19, (3, 1): 50, (4, 1): 5, ...}
should be
{(1, 3): 64, (1, 4): 18, (1, 2): 10, (11, 11): 19, ...}
I thought about sorting them and then doing something based on position in the dictionary, but this is not very easy to scale up. Input is welcome!
Use a frozenset for the dict key instead of a tuple. Then you can just add them as you go along, without worrying about ordering.
As @wim suggested, you should probably use a frozenset, then you can use collections.Counter and sum to cumulate the values into a new dictionary:
from collections import Counter
d = {(1, 3): 14, (1, 4): 13, (1, 2): 10, (11, 11): 19, (3, 1): 50, (4, 1): 5}
r = sum((Counter({frozenset(k): v}) for k, v in d.items()), Counter())
print(r)
# Counter({frozenset({1, 3}): 64, frozenset({11}): 19, frozenset({1, 4}): 18, frozenset({1, 2}): 10})
You may turn the Counter object into a vanilla dict and the keys back to tuples if you so wish using a dictionary comprehension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With