1

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?

0

1 Answer 1

2

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)}
Sign up to request clarification or add additional context in comments.

2 Comments

I want output to be {98:0.56, 106:0.33, 107:0.21}. How do i get that?
@Explore_SDN -- added custom class example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.