Hi forum,
I’m trying to sort dict with key of type of user defined class type.
I’m not clear on something.
-
Is dict ordered type in Python3.8. I mean preserve the insertion order may be not enough. It’ll be better that we can sort the dict in place. Not just sort’ed’ into list of tuple and get back to another dict. C++ has both std::map and std::unordered_map.
-
It seems the
__lt__
, the < function is enough for a user class to be sort’ed’ on dict. Are__hash__
,__eq__
,__ne__
useful too? -
PyCharm gives hint on line 25 for the argument to dict(). I do not know how to fix it. Do I need to provide a GetItem() function?
Thanks
class Item:
def __init__(self, name='', num=0):
self.name = name
self.num = num
# def __hash__(self):
# return hash((self.name, self.num))
# def __eq__(self, other):
# return (self.name, self.num) == (other.name, other.num)
def __lt__(self, other):
return (self.name, self.num) < (other.name, other.num)
# def __ne__(self, other):
# return not self == other
def __repr__(self):
return self.name + ',' + str(self.num)
def hello():
items = {Item('ccc', 3): 11, Item('bbb', 2): 12, Item('aaa', 1): 13}
logging.info('%s, %s', type(items), items)
items2 = dict(sorted(items.items(), key=lambda item: item[0])) # line 25: PyCharm: Unexpected type(s)
logging.info('%s, %s', type(items2), items2)
# Unexpected type(s): (List[Item]) Possible type(s): (SupportsKeysAndGetItem[Item, _VT]) (Iterable[Tuple[Any, Any]])
# output:
# <class 'dict'>, {ccc,3: 11, bbb,2: 12, aaa,1: 13}
# <class 'dict'>, {aaa,1: 13, bbb,2: 12, ccc,3: 11}