python - How to put key,value pair in dictionary in position based on sorted keys? -
i map in c++. know normal python dict dont support order. found ordereddict in collections. not work expected.
>>> odict = ordereddict() >>> odict['z'] = '1' >>> odict['a'] = '2' >>> odict['y'] = '3' >>> print(odict) ordereddict([('z', '1'), ('a', '2'), ('y', '3')])
but have order, this:
ordereddict([('a', '2'), ('y', '3'), ('z', '1')])
collections.ordereddict
remembers item insertion order. you're looking sorteddict part of blist third party package...
the alternative sort keys before pack them ordereddict
, things become un-sorted if need add more items ...
Comments
Post a Comment