Sort dictionary by Python value

4

I have a dictionary with the following format

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

I'd like to know if there's any way to sort it by value and print it on the screen. So the output is.

'158947719': 4
'186398060': 8    
'191725321': 10
'199846203': 42
'759147': 54 
    
asked by anonymous 18.12.2016 / 05:18

2 answers

4

You can use the sorted() function:

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 and on CodingGround .

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

    
18.12.2016 / 10:57
1

A dictionary in python has no order, in most cases it does not make sense to keep the order of the dictionary items.

However, OrderedDict ( also in python 2 ).

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

    
19.12.2016 / 19:44