SORT A PYTHON DICTIONARY BY VALUE

Sanjay Sharma

Total Post:45

Points:315
Posted by  Sanjay Sharma
 962  View(s)
Ratings:
Rate this:

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?

  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Sort a Python dictionary by value

    It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently orderless, but other types, such as lists and tuples, are not. So you need a sorted representation, which will be a list—probably a list of tuples.

    For instance,

    import operator
    x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
    sorted_x = sorted(x.items(), key=operator.itemgetter(1))
    sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.

    And for those wishing to sort on keys instead of values:

    import operator
    x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
    sorted_x = sorted(x.items(), key=operator.itemgetter(0))

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!