Sort dictionary by Python value

I have a dictionary with the following format

dic={759147': 54, '186398060': 8, '199846203': 42, '191725321': 10, '158947719': 4}

I would like to know if there is how to sort it by value and print on the screen. So that the output is.

'158947719': 4
'186398060': 8    
'191725321': 10
'199846203': 42
'759147': 54 
Author: Wilker, 2016-12-18

2 answers

Can use the function sorted():

dic = {'759147': 54, '186398060': 8, '199846203': 42, '191725321': 10, '158947719': 4}
for item in sorted(dic, key = dic.get):
    print (dic[item])

See working on ideone. E no repl.it. also I put on GitHub for future reference .

Just a detail, the most correct term would be to classify the dictionary .

 6
Author: Maniero, 2020-11-17 20:43:47

A python Dictionary has no order, in most cases it makes no sense to maintain the order of dictionary items.

But there is the OrderedDict (also in python 2 ).

Alternatively you can sort a list with the keys and access the values in the order of that list.

 2
Author: tovmeod, 2016-12-19 18:44:04