简体   繁体   中英

Going back and forth between sets and tuples in python

I have a dictionary with let's say n rows in which in each row I have a bunch of values and tuples as keys. Something like this:

a = {(-1,2):40, (4,5):10, (-6,1):20, (2,-3):30, ...}

now let's say I have another dictionary like this:

b = {(4,5):10, (-6,1):20, (-1,2):40, (2,-3):30, ...}

so basically b is a but the order of elements is not the same. The issue is that I couldn't come up with a good way to check this. I can't use sets as keys and quickly confirm a == b and if I put tuples as keys then a == b is false since the order is scrambled. I tried tuple(set()) them, didn't work either. So I was thinking about keeping the keys as tuple(set()) , kinda "untuple" them in an intermediate step, check, and tuple them back. I don't think unpacking helps here since I don't want to mix what's inside tuples like (4,5,-6,1,...) what I want to do eventually is to see if I already have this combination of tuples in my dictionary, no matter how the elements are ordered.

Let me know if I couldn't make myself clear, I'm a noob in programming so yeah, Thanks.

You're doing something else wrong, order is irrelevant in dictionaries...

In [1]: x = {(1,2):3, (4,5):6}                                                                                                            

In [2]: y = {(4,5):6, (1,2):3}                                                                                                            

In [3]: x == y                                                                                                                            
Out[4]: True

You could normalize the tuples in the two dictionaries to perform the comparison:

def normalized(d): return { tuple(sorted(k)):v for k,v in d.items() }

if normalized(a) == normalized(b):
    ...

Note that this is not very efficient and you should consider working with the normalized keys in the rest of the program (ie normalize the data as early as possible when it is read/received)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM