I have following two dictionaries
x = {0:[1,2,3], 1:[1,2,3], 2:[1,2,3]}
y = {0:[1,2,3], 1:[1,2,3], 2:[1,2,3]}
I need to check the similarity of these two dictionaries. I am using following code for that
shared_items = set(x.items()) & set(y.items())
But it gives me
TypeError: unhashable type: 'list'
error.
What is the reason for this issue and how to correct it.
A set
cannot contain a non-hashable object as it uses hashes for item lookup. Since you have list
values, which are mutable, adding those in a set
raises an error.
You will need to use tuple
values instead.
x = {1: (1, 2, 3), 2: (1, 2, 3)}
y = {0: (1, 2, 3), 1: (1, 2, 3)}
shared_items = set(x.items()) & set(y.items())
# shared_items: {(1, (1, 2, 3))}
Although, since values in a dict
are allowed to be mutable, you might want to settle for another data structure for a more general solution. The following will return a dict
of the shared key-value pairs.
x = {1: [1, 2, 3], 2: [1, 2, 3]}
y = {0: [1, 2, 3], 1: [1, 2, 3]}
shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]}
# shared_items: {1: [1, 2, 3]}
You can directly compare dictionnaries with ==
:
In [1]: x = {0:[1,2,3], 1:[1,2,3], 2:[1,2,3]}
In [2]: y = {0:[1,2,3], 1:[1,2,3], 2:[1,2,3]}
In [3]: shared_items = x == y
In [4]: shared_items
Out[4]: 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