Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare tuples with elements not in order

I have a two dicts that I'm converting bot to tuples . Both dict contain the same elements, but they are not generated using the same logic .

For example let's say I have a tuple like this :

(('a',5),('n',4),('c',8))

And the 2nd tuple is like that :

(('c',8),('n',4),('a',5))

Their original dicts is like that (probably, I can't know how will the elements be ordered in the dict however they are generated from two dicts that contains the same elements (no more, no less) :

{'a':5,'c': 8,'n':4}

For a human being both tuples are similar, but for a computer they are not .

How can I go with checking if two tuples are similar ?

like image 903
Anis Souames Avatar asked Feb 06 '23 08:02

Anis Souames


1 Answers

Sort both the tuple and compare them. For example:

>>> tuple_1 = (('a',5),('n',4),('c',8))
>>> tuple_2 = (('c',8),('n',4),('a',5))

# Non-sorted --> unequal; issue you are currently facing
>>> tuple_1 == tuple_2
False

# comparing sorted tuples -- equal 
>>> sorted(tuple_1) == sorted(tuple_2)
True

If the elements of both the tuples are unique, you may also compare them via using set as:

>>> set(tuple_1) == set(tuple_2)
True

As a side note, you do not have to convert the dict to tuple in order to compare the content of dictionaries. You may directly compare the dict objects as:

>>> {1: 2, 3: 4} == {3: 4, 1: 2}
True
like image 118
Moinuddin Quadri Avatar answered Feb 08 '23 14:02

Moinuddin Quadri