2

I'd like to convert a list of dicts into a set of dicts.

For example:

I have the following list:

my_list = [{k1:v1, k2:v2}, {k3:v3, k4:v4}]

I simply want to convert it easily to a set of these dicts.

As long as my lists were holding simple data like Strings, there was no problem with:

new_list = set(myList)

But if they hold dicts, they fall on

TypeError: unhashable type: 'dict'

I'd rather not iterating the list and add each item to the set. I'd rather have a straight forward method which will also support list of strings for example.

Is that possible?

martineau
  • 119,623
  • 25
  • 170
  • 301
dushkin
  • 1,939
  • 3
  • 37
  • 82
  • 5
    you cannot have a set of dicts and the reason is (as you noticed yourself) that dicts are not hashable. This is the only requirement for objects of a `set` and dicts among other data types do not fulfill it. – Ma0 Jun 22 '20 at 12:51
  • To simply remove duplicated list items. At first there were only string lists, but now I have to deal also with dict lists, and I hoped there could be a generic solution for both. – dushkin Jun 22 '20 at 12:53
  • 1
    Does this answer your question? [Remove duplicate dict in list in Python](https://stackoverflow.com/questions/9427163/remove-duplicate-dict-in-list-in-python) – Ma0 Jun 22 '20 at 12:54
  • 1
    You might find this answer very useful https://stackoverflow.com/questions/2703599/what-would-a-frozen-dict-be – Riccardo Bucco Jun 22 '20 at 12:59

2 Answers2

2

As the error suggests elements in a set must be hashable, which means that the must have a unique id (given by the hash method). You could create your own dict extension class that gives the dict a hash, e.g. the hash of all its keys. Or test/filter your list before converting it to a set. In short, a set cannot contain dicts.

Arcanefoam
  • 687
  • 7
  • 20
2

Python doesn't have a builtin 'frozendict' type. If you really want to emulate what a frozendict would do, then you might want to to store a hashable equivalent of a dict. For example:

my_list = [{k1:v1, k2:v2}, {k3:v3, k4:v4}]

my_set = set(frozenset(d.items()) for d in my_lst)

If you want to get your dicts back all you need to do is:

my_list = list(map(dict, my_set))
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50