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 ?
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
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