Use dicts as elements in a set in Python

Is there a way to put some dict objects into a set in Python using a simple method like a comparator function?

Here you could find several solutions that included a bunch of things that looked very complex and error prone (there seemed to be problems with iterating over the dict in undefined orders, etc.). It would be nice to do something like this, which is technically not mathematically justified, because two objects can have different information, but are estimated to be equal, but they cope with a lot of real use cases:

# One of the dicts: widget = { lunch: 'eggs', dunner: 'steak' } # Define a comparator function (ignores dinner) def comparator(widget1, widget2): return widget1['lunch'] > widget2['lunch'] widget_set = set([widget], comparator) 
+4
source share
1 answer

No, you can’t. You can add immutable values ​​to the set. This limitation is not only related to the ability to compare values; you need to check both for equality and for obtaining a hash value, and most of all the value should remain stable. Variable values ​​do not meet the latest requirement.

The dictionary can be made unchanged by turning it into a series of tuples with a key; if the values ​​are immutable, the following works:

 widget_set = {tuple(sorted(widget.items()))} # {..} is a set literal, Python 2.7 and newer 

This makes it possible to check for the presence of the same dictionary, at least for testing tuple(sorted(somedict.items())) in widget_set . Returning values ​​back to dict is a call to 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'} 
+5
source

Source: https://habr.com/ru/post/1480591/


All Articles