python dictionary sorting in descending order based on values

Viewed 206949

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.

11 Answers

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.

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

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

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

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