简体   繁体   中英

python: sorting key:value pair based on key

I have a dictionary as

    i={106:0.33,107:0.21,98:0.56}

I want to sort the key:value pairs based on keys. I am expecting output to look like following:

    {98:0.56, 106:0.33, 107:0.21}

When i use this:

    od = collections.OrderedDict(sorted(i.items()))
    print(od)

I am getting wrong output as:

    [(98,0.56),(106,0.33),(107,0.21)]

Can anyone please help me with correct code for this?

An OrderedDict remembers the order that you added items to the dictionary, not the sort order.

But you can easily create a sorted list from a regular dictionary. For example:

>>> list1={106:0.33,107:0.21,98:0.56}
>>> sorted(list1.items())
[(98, 0.56), (106, 0.33), (107, 0.21)]

Or if you want it in an OrderedDict, just apply the OrderedDict after the sort:

>>> from collections import OrderedDict
>>> 
>>> list1={106:0.33,107:0.21,98:0.56}
>>> OrderedDict(sorted(list1.items()))
OrderedDict([(98, 0.56), (106, 0.33), (107, 0.21)])

But a regular dict has no concept of sort order, so you can't sort the dictionary itself.

However, if you really want that display, you can create your own class:

>>> from collections import OrderedDict
>>> class MyDict(OrderedDict):
...     def __repr__(self):
...         return '{%s}' % ', '.join(str(x) for x in self.items())
... 
>>> list1={106:0.33,107:0.21,98:0.56}
>>> MyDict(sorted(list1.items()))
{(98, 0.56), (106, 0.33), (107, 0.21)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM