user3654650
user3654650

Reputation: 6103

How to put key,value pair in dictionary in position based on sorted keys?

I look for something like map in C++. I know normal python dict dont support order. I found ordereddict in collections. But it do not work as expected.

>>> odict = OrderedDict()
>>> odict['z'] = '1'
>>> odict['a'] = '2'
>>> odict['y'] = '3'
>>> print(odict)
OrderedDict([('z', '1'), ('a', '2'), ('y', '3')])

But I would like to have order, like this:

OrderedDict([('a', '2'), ('y', '3'), ('z', '1')])

Upvotes: 0

Views: 357

Answers (3)

Hackaholic
Hackaholic

Reputation: 19733

Ordered dict remembers the order in the way they are updated
you can use sorted to sort:

>>> my_dict = {'a': 1, 'c': 3, 'b': 4}
>>> [x for x in sorted(a.items(),key=lambda x:x[0])]  # sorted on keys
[('a', 1), ('b', 4), ('c', 3)]

if you want to sort on values:

>>> [x for x in sorted(a.items(),key=lambda x:x[1])]
[('a', 1), ('c', 3), ('b', 4)]

Upvotes: 1

101
101

Reputation: 8989

You can't reorder an ordered dict, the order is determined when the data is added. But you can make a new one based on the original:

odict = OrderedDict([('z', 1), ('a', 2), ('y', 3)])
odict_sorted = OrderedDict(sorted(odict.iteritems()))

# gives OrderedDict([('a', 2), ('y', 3), ('z', 1)])

Upvotes: 0

mgilson
mgilson

Reputation: 309899

collections.OrderedDict remembers item insertion order. You're looking for something like a sorteddict which is part of the blist third party package...

The alternative is to sort the keys before you pack them into the OrderedDict, but things will likely become un-sorted if you need to add more items ...

Upvotes: 2

Related Questions