How do I sort a dictionary by value

0 votes
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.

I can sort on the keys, but how can I sort based on the values?
Mar 13, 2019 in Python by Mukesh

1 answer to this question.

0 votes

If you construct a dictionary with the words as keys and the number of occurrences of each word as value, example:

from collections import defaultdict
d = defaultdict(int)
for w in text.split():
  d[w] += 1

then you can get a list of the words, ordered by frequency of use with sorted(d, key=d.get).

the sort iterates over the dictionary keys, using the number of word occurrences as a sort key .

for w in sorted(d, key=d.get, reverse=True):
  print w, d[w]
answered Mar 13, 2019 by Trisha

Related Questions In Python

0 votes
1 answer

How do I sort a dictionary by value?

It is not possible to sort a ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 58,140 points
0 votes
1 answer

How do I sort a list of dictionaries by a value of the dictionary?

Hello @kartik, import operator To sort the list of ...READ MORE

answered Apr 23, 2020 in Python by Niroj
• 82,820 points
0 votes
3 answers

How can I sort a dictionary by key in python?

Another way could be: color_dict = {'red':'#FF0000',           'green':'#008000',           'black':'#000000',           'white':'#FFFFFF'} for ...READ MORE

answered Dec 28, 2020 in Python by Thomas Walenta
0 votes
2 answers

In Python, how do I read a file line-by-line into a list?

readline function help to  read line in ...READ MORE

answered Jun 21, 2020 in Python by sahil
• 560 points
0 votes
1 answer

How to sort dictionary by value python

This would work: d = sorted(data, key = ...READ MORE

answered Nov 2, 2018 in Python by Nabarupa
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,402 views
0 votes
0 answers
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
0 votes
1 answer

How to merge two dictionaries in a single expression?

In Python 3.5 or greater: z = {**x, ...READ MORE

answered Mar 13, 2019 in Python by Trisha