python-3.xlistdictionaryset-operations

How do I avoid a "TypeError: unhashable type: 'dict'" when computing list differences?


I'm using Python 3.8. I have two lists, with each element being a dict ...

>>> existing_dicts = [{"id": 1}, {"id": 2}]
>>> cur_dicts = [{"id": 2}]

I wanted to find the dicts that were no longer in "cur_dicts" that were originally in "existing_dicts". So in the above example,

{"id": 1}

is my desired result since it is in "existing_dicts" but not in "cur_dicts". I tried the below to find the difference ...

>>> deleted_dicts = list(set(existing_dicts) - set(cur_dicts))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

What's a better way to do this?


Solution

  • The set approach is not working since your dictionaries elements of lists. It seems that turning lists of dictionaries into sets is not allowed.

    Instead, you can use a list comprehension where you check if any element in the list existing_dict is in the cur_dicts,

     deleted_dicts = [x for x in existing_dicts if not (x in cur_dicts)]
    

    If the dictionary is not in cur_dicts, it is added to deleted_dicts. This relies on the fact that dictionaries can be compared for equality with an == operator.

    Full example, extended with duplicate entries and larger dictionaries:

    existing_dicts = [{"id": 1}, {"id": 2}, {"id": 2}, {"id": 2, "id2" : 3}, {"id": 1, "id2": 2}]
    cur_dicts = [{"id": 2}, {"id": 1, "id2": 2}]
    
    deleted_dicts = [x for x in existing_dicts if not (x in cur_dicts)]
    print(deleted_dicts)