5

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.

Malintha
  • 4,512
  • 9
  • 48
  • 82

4 Answers4

5

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]}
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
2

It unfortunately won't work in Python3x, since a list is considered unhashable in the same. How about just comparing them directly, this should work for most scenarios.

x == y
hspandher
  • 15,934
  • 2
  • 32
  • 45
2

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
Adam Jaamour
  • 1,326
  • 1
  • 15
  • 31
0

You can't make a set of lists. Lists are "unhashable", and essentially no mutable objects are (more info here). If you want to do something similar, check out this answer.

Jay Calamari
  • 573
  • 4
  • 17