0

I have a dictionary, say

{'name4': 380, 'name2': 349, 'name3': 290, 'name1': 294}

I have sorted the dictionary based on the values using the sorted method and the result is a list of tuples

[('name3', 290), ('name1', 294), ('name2', 349), ('name4', 380)]

But, when I try to convert this list of tuples back to dictionary, it's back again to the old structure:

{'name4': 380, 'name2': 349, 'name3': 290, 'name1': 294}

I want the sorted list to be made into dictionary as it is. I have used dict() and manually used for loop to assign the values. But it's again leading to the same result.

Could anyone help me on this?

glibdud
  • 7,550
  • 4
  • 27
  • 37
user3275349
  • 69
  • 1
  • 9
  • 3
    Dictionaries are not ordered (prior to Python 3.6), you may want to pass the sorted items to an `OrderedDict` – Chris_Rands Jan 10 '17 at 14:15
  • 1
    Possible duplicate of [Python dictionary, how to keep keys/values in same order as declared?](http://stackoverflow.com/questions/1867861/python-dictionary-how-to-keep-keys-values-in-same-order-as-declared) – bereal Jan 10 '17 at 14:33

4 Answers4

4

The keys in a dictionary are, because of the dictionary's underlying structure (hash map), unordered. You have to order the keys yourself when you iterate the keys (i.e. by doing sorted(dict.keys()) or some other sorting method - if you want to sort by value, you still have to do that manually).

Rok Povsic
  • 4,626
  • 5
  • 37
  • 53
2

Instead of using an unordered dict you could use collections.OrderedDict which remembers the the insertion order:

>>> from collections import OrderedDict
>>> odict = OrderedDict([('name3', 290), ('name1', 294), ('name2', 349), ('name4', 380)])
>>> odict
OrderedDict([('name3', 290), ('name1', 294), ('name2', 349), ('name4', 380)])

It supports the same operations like a normal dict (from the documentation of OrderedDict):

Return an instance of a dict subclass, supporting the usual dict methods. An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

Consider using an ordered-dict which maintain the information about the order in which the keys are entered.

 OrderedDict({index:i for i, index in enumerate(some_list)})
Shagun Sodhani
  • 3,535
  • 4
  • 30
  • 41
-1

You can refer below code to print the sorted dictionary for the given data:

data = [('name3', 290), ('name1', 294), ('name2', 349), ('name4', 380)]

print(sorted(dict(data).items()))
Dharman
  • 30,962
  • 25
  • 85
  • 135
ANK
  • 537
  • 7
  • 12