Home How do I sort a dictionary by value?
Reply: 0

How do I sort a dictionary by value?

user10523
1#
user10523 Published in September 21, 2018, 8:02 am

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?

Note: I have read Stack Overflow question How do I sort a list of dictionaries by values of the dictionary in Python? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.

share|improve this question
  • 7
    The dictionary data structure does not have inherent order. You can iterate through it but there's nothing to guarantee that the iteration will follow any particular order. This is by design, so your best bet is probaly using anohter data structure for representation. – Daishiman Jul 5 '10 at 2:08
  • 108
    "sorted()" can operate on dictionaries (and returns a list of sorted keys), so I think he's aware of this. Without knowing his program, it's absurd to tell someone they're using the wrong data structure. If fast lookups are what you need 90% of the time, then a dict is probably what you want. – bobpaul Feb 15 '13 at 19:04
  • 6
    For those suggesting that this is a duplicate of stackoverflow.com/questions/72899/… , that question is marked as a duplicate of this question. – Marcin Sep 18 '13 at 16:36
  • 5
    If possible, instantiate a NumPy Series from the dictionary and sort it using pandas.Series.order – Dror Nov 27 '14 at 14:22
  • 1
    @Daishiman The base class might not be ordered but OrderedDict is of course. – Taylor Edmiston Sep 9 '17 at 1:10

41 Answers 41

active oldest votes
1 2 next
up vote 3613 down vote accepted
+500
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.510277 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO