0

I was confused weather or not dictionaries are hashable since you can check if a dictionary is in a list using the "in" operator

>>> test_list = [{'key1': 'a'}, {'key2': 'b'}]
>>> test_dict = {'key1': 'a'}
>>> test_dict in test_list
True
>>> {'key1': 'b'} in test_list
False
>>> {'key2': 'a'} in test_list
False

Running set on a dictionary doesn't exactly give a good result for this so this wasn't happening either behind the scenes

>>> set(test_dict)
{'key1'}

And it doesn't seem to be only checking the keys/values/items

>>> test_dict.keys() in test_list
False
>>> test_dict.values() in test_list
False
>>> test_dict.items() in test_list
False
Filip
  • 138
  • 1
  • 14

1 Answers1

0

After a little digging around it looks like what I was looking for is an explanation for the list class's __contains__ magic function

This function can be found here: https://github.com/python/cpython/blob/main/Objects/listobject.c#L443C5-L443C5

But to quote a roughly equivalent version from another answer https://stackoverflow.com/a/67409987/2337471

>>> any(test_dict is item or test_dict == item for item in test_list)
True

This can be further deduced to only this part in this case

>>> any(test_dict == item for item in test_list)
True

So, when we check for the items in the list

>>> for item in test_list:
...   print(item)
{'key1': 'a'}
{'key2': 'b'}

It becomes apparent that

>>> {'key1': 'a'} == {'key1': 'a'}
True
Filip
  • 138
  • 1
  • 14