Hello
Hello

Reputation: 11

dictionary with tuple as key

Currently I created a dictionary that uses tuple pairs as keys. My dictionary currently counts pairs such as (a,b) and (b,a) separately, but I ultimately want (a,b) == (b,a).

Currently that portion of my code looks like this:

final = collections.defaultdict(list)
for a,b in pairs:

    final[(a[0],b[0])].append((a[2],a[1]))
    final[(b[0],a[0])].append((b[2],b[1]))

Would I have to check if the (b,a) of the (a,b) already exists in the dictionary prior to adding it? Or do I fix the dictionary after it's all completed?

Upvotes: 1

Views: 1473

Answers (2)

Sanju Yadav
Sanju Yadav

Reputation: 36

pairs = [frozenset([1,2]), frozenset([3,4]), frozenset([2,1]), 
frozenset([5,6]), frozenset([7,8]), frozenset([6,5])]

for pair in pairs:
    pair_count.update({pair: pair_count.get(pair, 0) + 1})

pair_count
{frozenset([5, 6]): 2, frozenset([1, 2]): 2, frozenset([8, 7]): 1, frozenset([3, 4]): 1}

Upvotes: 0

Alex Hall
Alex Hall

Reputation: 36033

Use frozenset([a, b]). Sets compare equal regardless of order, but only frozensets can be used as dictionary keys because they're immutable.

If a == b though your key will be equal to frozenset([a]). If this is a problem, we can make a plan.

Upvotes: 2

Related Questions