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 12, 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 12, 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
• 57,550 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 in Python by Niroj
• 42,000 points
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 in Python by sahil
• 540 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
+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 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,177 views
0 votes
0 answers
+4 votes
6 answers
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 12, 2019 in Python by Trisha