Search code examples
pythonpython-2.7dictionaryordereddictionary

key value pair position change when converting sorted ordereddict to dict


So I need to convert my dictionary to a dictionary sorted by values:

from collections import OrderedDict
from collections import OrderedDict
import json
d = {"third": 3, "first": 1, "fourth": 4, "second": 2}
d_sorted_by_value = OrderedDict(sorted(d.items(), key=lambda x: x[1]))

# OrderedDict([('first': 1), ('second': 2), ('third': 3), ('fourth': 4)])
# print (OrderedDict)
def ordereddict_to_dict(d_sorted_by_value):
    for k, v in d_sorted_by_value.items():
        if isinstance(v, dict):
            d_sorted_by_value[k] = ordereddict_to_dict(v)
    print dict(d_sorted_by_value)
d = {"third": 3, "first": 1, "fourth": 4, "second": 2}
d_sorted_by_value = OrderedDict(sorted(d.items(), key=lambda x: x[1]))
print d_sorted_by_value
ordereddict_to_dict(d_sorted_by_value)

On printing d_sorted_by_value I get: OrderedDict([('first', 1), ('second', 2), ('third', 3), ('fourth', 4)])

which is not what i want even though it can be used as a dict. So the function to convert it to dict was called whch gave me the following output:

{'second': 2, 'third': 3, 'fourth': 4, 'first': 1}

As you can see the key value pair: 'first':1' beomes the last element on conversion, what am i doing worng here? The desired output that i want is :

{'first': 1,'second': 2, 'third': 3, 'fourth': 4}

Please guide in the right direction. Thanks!!


Solution

  • What you are asking is not possible.

    A dict object in Python <3.7 is not considered to be ordered. It is internally ordered in 3.6, but this is considered an implementation detail.

    Converting a dict to an OrderedDict and then back to a dict object should not be assumed to maintain order.

    Your options are:

    1. Use regular dict for an unordered collection.
    2. Use OrderedDict for an ordered collection.