Use Dicts As Items In A Set In Python
Is there a way to put some dict objects into a set in Python by using a simple method, like a comparator function? Came across a few solutions on here that involved a bunch of stuf
Solution 1:
No, you cannot. You can only put immutable values into a set. This restriction has to do with more than just being able to compare values; you need to test both for equality and be able to obtain a hash value, and most of all the value has to remain stable. Mutable values fail that last requirement.
A dictionary can be made immutable by turning it into a series of key-value tuples; provided the values are immutable too, the following works:
widget_set = {tuple(sorted(widget.items()))} # {..} is a set literal, Python 2.7 and newer
This makes it possible to test for the presence of the same dictionary by testing for tuple(sorted(somedict.items())) in widget_set
at least. Turning the values back into a dict
is a question of calling dict
on it:
dict(widget_set.pop())
Demo:
>>>widget = {...'lunch': 'eggs',...'dunner': 'steak'...}>>>widget_set = {tuple(sorted(widget.items()))}>>>tuple(sorted(widget.items())) in widget_set
True
>>>dict(widget_set.pop())
{'lunch': 'eggs', 'dunner': 'steak'}
Post a Comment for "Use Dicts As Items In A Set In Python"