love2code love2code - 5 months ago 14x
Python Question

How to form a set of dictionaries

My intent is to have a list with unique dictionaries. For this I have figured out that using sets would be a good option and here is what I have been trying.

Here is what I have been doing:

import json
mylist = [{'id':1,'name':'john', 'age':34},{'id':1,'name':'john', 'age':34},{'id':2,'name':'hanna', 'age':30}]
myset = set(json.dumps(mylist[0]))

And here is the output

{'id': 1, 'age': 34, 'name': 'john'} #actual dictionary element
{'e', 'j', 'h', 'i', ':', '"', 'o', '3', 'n', 'a', '}', '4', ' ', ',', 'm', 'g', '{', '1', 'd'} #dictionary element in set

Since we cannot store dictionary objects in a sets I am converting the elements to string first using json.dumps . Basically set is singularizing my dictionary elements. How can I store dictionary elements in a set. I understand we cannot store dict objects in a set hence I am converting them to string 1st and then adding in set.


A tuple of tuples should work like so:

>>> mylist = [{'id':1,'name':'john', 'age':34},{'id':1,'name':'john', 'age':34},
{'id':2,'name':'hanna', 'age':30}]
>>> myset = {tuple(d.items()) for d in mylist}
>>> myset
{(('name', 'hanna'), ('id', 2), ('age', 30)), (('name', 'john'), ('id', 1), ('age', 34))}

# Converting back to dictionary
>>> [dict(i) for i in myset]
[{'name': 'hanna', 'id': 2, 'age': 30}, {'name': 'john', 'id': 1, 'age': 34}]


As @Raymond suggest, perhaps first sorting the tuples like so would be a smart idea.

>>> myset = {tuple(sorted(d.items())) for d in mylist}

Dictionaries are in arbitrary order so sorting it makes sure the tuples are always the same.