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 in Python by Mukesh
22 views

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 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,300 points
38 views
0 votes
1 answer

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

with open(fname) as f:     content = f.readlines() # you ...READ MORE

answered Oct 9, 2018 in Python by SDeb
• 13,210 points
143 views
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
79 views
0 votes
1 answer

How do I remove an element from a list by index in Python?

You can use the pop() method to ...READ MORE

answered Jun 21 in Python by Nisa
• 1,090 points
841 views
+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 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 412 views
+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 in Python by Trisha
60 views