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
436 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 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,090 points
551 views
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,880 points
546 views
0 votes
0 answers

How do I sort a dictionary by value?

I have some dictionary of values that ...READ MORE

Sep 21, 2022 in Python by Samuel
• 460 points
301 views
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
833 views
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
• 580 points
1,469 views
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 4,060 views
0 votes
1 answer
+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,790 points
3,480 views
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
378 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP