Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Add Values and Remove Entry for Tuple Permutations in a Dictionary

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!

like image 437
Flow Nuwen Avatar asked Apr 16 '26 08:04

Flow Nuwen


2 Answers

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.

like image 78
wim Avatar answered Apr 19 '26 00:04

wim


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.

like image 28
Moses Koledoye Avatar answered Apr 19 '26 00:04

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!