Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type error while comparing two dictionaries [duplicate]

Tags:

python

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.

like image 355
Malintha Avatar asked Jun 14 '18 12:06

Malintha


2 Answers

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]}
like image 128
Olivier Melançon Avatar answered Sep 23 '22 16:09

Olivier Melançon


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
like image 20
Adam Jaamour Avatar answered Sep 23 '22 16:09

Adam Jaamour