1

I want to sort a dictionary by its values(of integers) back to a Dictionary. Like following :

di = {'h': 10, 'e':5, 'l':8}

What I want is :

sorted_di = {'e':5, 'l':8, 'h':10}

I searched a lot and got to sort it into list of tuples, like:

import operator
sorted_li = sorted(di.items(),key=operator.itemgetter(1),reverse=True)
print(sorted_li)

Gives :

[('e',5),('l':8),('h':10)]

But I want it to be a dictionary again.

Can anyone help me please??

FightWithCode
  • 2,190
  • 1
  • 13
  • 24

3 Answers3

2

Are dictionaries ordered in Python 3.6+?

They are insertion ordered. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior).

i.e.

  • Pre-3.6:

    >>> from collections import OrderedDict
    ...
    >>> OrderedDict(sorted_li)
    OrderedDict([('e', 5), ('l', 8), ('h', 10)])
    
  • 3.6+:

    >>> dict(sorted_li)
    {'e':5, 'l':8, 'h':10}
    
meowgoesthedog
  • 14,670
  • 4
  • 27
  • 40
0
di = {'h': 10, 'e':5, 'l':8}
temp_list = []
for key,value in di.items():
    temp_tuple = (k,v)
    temp_list.append(temp_tuple)
temp_list.sort()
for x,y in temp_list:
    dict_sorted = dict(temp_list)
print(dict_sorted)
  • Code only answers are discouraged on SO. Please supplement the code you have provided as an answer with why it solves OP's issue. – d_kennetz Feb 25 '19 at 20:37
0

You can try this:

di = {'h': 10, 'e':5, 'l':8}
tuples = [(k, di[k]) for k in sorted(di, key=di.get, reverse=False)]
sorted_di = {}
for i in range(len(di)):
    k = tuples[i][0]
    v = tuples[i][1]
    sorted_di.update({k: v})
print(sorted_di)  # {'e': 5, 'l': 8, 'h': 10}
Laurent Bristiel
  • 6,819
  • 34
  • 52