python dictionary sorting in descending order based on values

Question:

I want to sort this dictionary d based on value of sub key key3 in descending order. See below:

d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }

So final dictionary would look like this.

d = { '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
    }

My approach was to form another dictionary e from d, whose key would be value of key3 and then use reversed(sorted(e)) but since value of key3 can be same, so dictionary e lost some of the keys and their values. makes sense?

How I can accomplish this? This is not a tested code. I am just trying to understand the logic.

Asked By: NullException

||

Answers:

Dictionaries do not have any inherent order. Or, rather, their inherent order is “arbitrary but not random”, so it doesn’t do you any good.

In different terms, your d and your e would be exactly equivalent dictionaries.

What you can do here is to use an OrderedDict:

from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(), 
                                  key=lambda kv: kv[1]['key3'], reverse=True))

The original d has some arbitrary order. d_ascending has the order you thought you had in your original d, but didn’t. And d_descending has the order you want for your e.


If you don’t really need to use e as a dictionary, but you just want to be able to iterate over the elements of d in a particular order, you can simplify this:

for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
    do_something_with(key, value)

If you want to maintain a dictionary in sorted order across any changes, instead of an OrderedDict, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an OrderedDict that re-sorts itself as necessary, etc.

Answered By: abarnert

Python dicts are not sorted, by definition. You cannot sort one, nor control the order of its elements by how you insert them. You might want to look at collections.OrderDict, which even comes with a little tutorial for almost exactly what you’re trying to do: http://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes

Answered By: John Zwinck

you can make use of the below code for sorting in descending order and storing to a dictionary:

        listname = []  
        for key, value in sorted(dictionaryName.iteritems(), key=lambda (k,v): (v,k),reverse=True):  
            diction= {"value":value, "key":key}  
            listname.append(diction)
Answered By: Dibin Joseph

List

dict = {'Neetu':22,'Shiny':21,'Poonam':23}
print sorted(dict.items())
sv = sorted(dict.values())
print sv

Dictionary

d = []
l = len(sv)
while l != 0 :
    d.append(sv[l - 1])
    l = l - 1
print d`
Answered By: neetu chaudhary

A short example to sort dictionary is desending order for Python3.

a1 = {'a':1, 'b':13, 'd':4, 'c':2, 'e':30}
a1_sorted_keys = sorted(a1, key=a1.get, reverse=True)
for r in a1_sorted_keys:
    print(r, a1[r])

Following will be the output

e 30
b 13
d 4
c 2
a 1

sort dictionary ‘in_dict’ by value in decreasing order

sorted_dict = {r: in_dict[r] for r in sorted(in_dict, key=in_dict.get, reverse=True)}

example above

sorted_d = {r: d[r] for r in sorted(d, key=d.get('key3'), reverse=True)}
Answered By: Vegard Sangolt

You can use the operator to sort the dictionary by values in descending order.

import operator

d = {"a":1, "b":2, "c":3}
cd = sorted(d.items(),key=operator.itemgetter(1),reverse=True)

The Sorted dictionary will look like,

cd = {"c":3, "b":2, "a":1}

Here, operator.itemgetter(1) takes the value of the key which is at the index 1.

Answered By: Hemang Vyas

Whenever one has a dictionary where the values are integers, the Counter data structure is often a better choice to represent the data than a dictionary.

If you already have a dictionary, a counter can easily be formed by:

c = Counter(d['123'])

as an example from your data.

The most_common function allows easy access to descending order of the items in the counter

The more complete writeup on the Counter data structure is at https://docs.python.org/2/library/collections.html

Answered By: demongolem

You can use dictRysan library. I think that will solve your task.

import dictRysan as ry

d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }

changed_d=ry.nested_2L_value_sort(d,"key3",True)
print(changed_d)
Answered By: Rafsan Jany
f= {273: 6, 272: 2, 2: 1, 3083: 1, 281: 1, 2490: 5, 366: 5, 1945: 4, 869: 1, 1398: 1, 1920: 5, 3061: 2, 862: 1}
        
sorted_d = dict( sorted(f.items(), key=operator.itemgetter(1),reverse=True))

print('Dictionary in descending order by value : ',sorted_d)
Answered By: Pramoda KV

Here I am adding a generic solution to the problem.

Input: d = {"a":1, "b":2, "c":3}
Output: d= {"c":3, "b":2, "a":1}

import operator
dict(sorted(d.items(),key=operator.itemgetter(1),reverse=True))

Above code return a dict with sorted value.

sorted(d.items(),key=operator.itemgetter(1),reverse=True)

This line will return [(‘c’, 3), (‘b’, 2), (‘a’, 1)] -> Sorted List of tuples

   sql="select id, name, client_name, server_id, idsubdatatable from analytics_data where status=1;"
    conn.execute(sql,)
    result=conn.fetchall()
    for value in result:
        data_dict={}
        data_dict['id']=value[0]
        data_dict['name']=value[1]
        data_dict['client_name']=value[2]
        data_dict['server_id']=value[3]
        data_dict['idsubdatatable']=value[4]
        data_result.append(data_dict)
    data_result = sorted(data_result, key=lambda i: i['idsubdatatable'],reverse=True)
    return (json.dumps({'data': data_result,'status':"SUCCESS"}))

if dictionary value of Key idsubdatatable in database is like 3,5,1,7,2 etc then it will return 7,5,3,2,1

Answered By: abhishek kumar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.