How to Sort a Python Dictionary by Keys or Values

Python is a free, interpreted, object-oriented programming language with a natural language syntax, large standard libraries, extensive error handling and flexible data structures. In Python, you use the dictionary data type to define one-to-one relationships between items. For example, you may want to create a dictionary to contain a child's name and age. Continuing the example, you can sort the dictionary in ascending order by the child's name, which is the key, or by the age, which is the value.

Instructions

    • 1

      Open your Python editor.

    • 2

      Load the operator module and itemgetter function by typing the following, then pressing "Enter."

      from operator import itemgetter

    • 3

      Sort the dictionary by key by typing the following, then pressing "Enter."

      s = {'ben':2, 'amy':3, 'zelda':1};

      sort_s = sorted(s.iterkeys());

      print s;

      Python sorts the dictionary by keys or student names and returns:

      {'amy': 3, 'ben': 2, 'zelda': 1}

    • 4

      Sort the dictionary by values by typing the following, then pressing "Enter."

      s = {'amy': 2, 'ben': 3, 'zelda': 1};

      sorted(s.items(), key=itemgetter(1));

      Python sorts the dictionary by value or student age in ascending order and returns:

      [('zelda', 1), ('amy', 2), ('ben', 3)]

Related Searches:

References

Comments

Related Ads

Featured