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?
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_dictis in thecur_dicts,If the dictionary is not in
cur_dicts, it is added todeleted_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: