Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why dictionary values comparison doesn't work in python

I want to compare the values of two dict if the frequency of elements are the same or not, elements can be different but their frequency should be the same.

dict1 = {'a':1, 'b':2, 'c':3}
dict2 = {'x':1, 'y':2, 'z':3}

# when I do a comparison of values, it doesn't work

print(dict1.values())
print(dict2.values())

if dict1.values() == dict2.values():
    print("Equal")
else:
    print("Not Equal")

Output:

dict_values([1, 2, 3])
dict_values([1, 2, 3])
Not Equal

So even though the output of dict.values() is same but they are not equal. Is this comparison not allowed and is there any other way to do the same?

like image 260
Aman Chourasiya Avatar asked Oct 29 '25 14:10

Aman Chourasiya


2 Answers

The method dict.values() does not return a list but a view into the dictionary. You need to consume it fully to obtain a list that can be compared:

if list(dict1.values()) == list(dict2.values()):
    print("Equal")
else:
    print("Not Equal")

Note that this comparison will only work if values are ordered the same in both dictionaries. You might want to ensure order by sorting:

if sorted(dict1.values()) == sorted(dict2.values()):
    print("Equal")
else:
    print("Not Equal")

As sorted() returns a list, we don't need the list() call anymore.

like image 133
ypnos Avatar answered Oct 31 '25 05:10

ypnos


This is documented:

An equality comparison between one dict.values() view and another will always return False. This also applies when comparing dict.values() to itself

Perhaps because they provide a dynamic view, you need to "freeze" the values taken from the view and then compare. One way is to cast them to tuples at the comparison instant:

>>> tuple(dict1.values()) == tuple(dict2.values())
True
like image 20
Mustafa Aydın Avatar answered Oct 31 '25 06:10

Mustafa Aydın



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!