dictionary - Use dicts as items in a set in Python -


is there way put dict objects set in python using simple method, comparator function?

came across few solutions on here involved bunch of stuff looked complex , error-prone (seemed problems iterating on dict in undefined orders, etc...). nice technically not mathematically valid because 2 objects can have different information, evaluated equal, works great plenty of real life use cases:

# 1 of dicts: widget = {      lunch:  'eggs',      dunner: 'steak' }  # define comparator function (ignores dinner) def comparator(widget1, widget2):      return widget1['lunch'] > widget2['lunch']  widget_set = set([widget], comparator) 

no, cannot. can put immutable values set. restriction has more being able compare values; need test both equality , able obtain hash value, , of value has remain stable. mutable values fail last requirement.

a dictionary can made immutable turning series of key-value tuples; provided values immutable too, following works:

widget_set = {tuple(sorted(widget.items()))}  # {..} set literal, python 2.7 , newer 

this makes possible test presence of same dictionary testing tuple(sorted(somedict.items())) in widget_set @ least. turning values dict 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'} 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -