Home > Back-end >  How to sort python dictionary by value and key
How to sort python dictionary by value and key

Time:02-04

I want to sort the dictionary by keys and values.

d = {'i': 1, 'live': 2, 'in': 2, 'bangalore': 2, 'is': 1, 'good': 1, 'city': 1, 'to': 1}

Output will be

{'bangalore': 2, 'in': 2, 'live': 2, 'city': 1, 'good': 1, 'i': 1, 'is': 1, 'to': 1}

CodePudding user response:

The linked question's answer can be adapted to your question:

d = {k: v for k, v in sorted(d.items(), key = lambda x: (-x[1], x[0]))}

For your example

d = {'i': 1, 'live': 2, 'in': 2, 'bangalore': 2, 'is': 1, 'good': 1, 'city': 1, 'to': 1}
d = {k: v for k, v in sorted(d.items(), key = lambda x: (-x[1], x[0]))}
print(d)

we get

{'bangalore': 2, 'in': 2, 'live': 2, 'city': 1, 'good': 1, 'i': 1, 'is': 1, 'to': 1}

as requested.

CodePudding user response:

sorting by key, then value is a simple sort operation on items:

d = dict(sorted(d.items()))

print(d)
{'bangalore': 2, 'city': 1, 'good': 1, 'i': 1, 'in': 2, 
 'is': 1, 'live': 2, 'to': 1}

To sort first on value then key, you can use the reversed tuples from the dictionary's items() as your sort key:

d = dict(sorted(d.items(),key=lambda kv:kv[::-1]))

print(d)
{'city': 1, 'good': 1, 'i': 1, 'is': 1, 'to': 1, 
 'bangalore': 2, 'in': 2, 'live': 2}
  •  Tags:  
  • Related