python dictionary sorting in descending order based on values

PythonDictionary

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Solution 3 - Python

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.

Solution 4 - Python

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

Solution 5 - Python

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)

Solution 6 - Python

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)}


 

Solution 7 - Python

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`

Solution 8 - Python

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)

Solution 9 - Python

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

Solution 10 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNullExceptionView Question on Stackoverflow
Solution 1 - PythonabarnertView Answer on Stackoverflow
Solution 2 - PythonHafiz Muhammad ShafiqView Answer on Stackoverflow
Solution 3 - PythonHemang VyasView Answer on Stackoverflow
Solution 4 - PythonJohn ZwinckView Answer on Stackoverflow
Solution 5 - PythonDibin JosephView Answer on Stackoverflow
Solution 6 - PythonVegard SangoltView Answer on Stackoverflow
Solution 7 - Pythonneetu chaudharyView Answer on Stackoverflow
Solution 8 - PythonPramoda KVView Answer on Stackoverflow
Solution 9 - PythondemongolemView Answer on Stackoverflow
Solution 10 - PythonRafsan JanyView Answer on Stackoverflow