July 25, 2018
How to sort a dictionary in python by keys and values
Introduction
Welcome to a new Python code snippets post. Below, you can find a summary of helpful Python syntax for that purpose…
Sorting type | Python 2 syntax | Python 3 syntax |
---|---|---|
Sorted dictionary keys | sorted(dict) | sorted(dict) |
Sorted dictionary values | sorted(dict.itervalues()) | sorted(dict.values()) |
Sorted dictionary items by value | sorted(dict.iteritems(), key = lambda x : x[1]) | sorted(dict.items(), key = lambda x : x[1]) |
Sorting in reverse order | sorted(dict, reverse=True) | sorted(dict, reverse=True) |
Ordered dictionary | collections.OrderedDict(dict.iteritems()) | collections.OrderedDict(dict.items()) |
Let us now take some examples…
Sorted dictionary keys
1 2 |
dict = {'A':3, 'C':1, 'B':2} print(sorted(dict)) |
This will print…
1 |
['A', 'B', 'C'] |
Sorted dictionary values
1 2 3 4 5 |
dict = {'A':3, 'C':1, 'B':2} # This is Python 2 syntax. If you are using # Python 3 then use: # dict.values() print(sorted(dict.itervalues())) |
This will print…
1 |
[1, 2, 3] |
Sorted dictionary items by value
1 2 3 4 5 |
dict = {'A':3, 'C':1, 'B':2} # This is Python 2 syntax. If you are using # Python 3 then use: # dict.items() print(sorted(dict.iteritems(), key = lambda x : x[1])) |
This will print…
1 |
[('C', 1), ('B', 2), ('A', 3)] |
Sorting in reverse order
1 2 3 4 5 |
dict = {'A':3, 'C':1, 'B':2} # Python 2 syntax print(sorted(dict, reverse=True)) print(sorted(dict.itervalues(), reverse=True)) print(sorted(dict.iteritems(), key = lambda x : x[1], reverse=True)) |
This will print…
1 2 3 |
['C', 'B', 'A'] [3, 2, 1] [('A', 3), ('B', 2), ('C', 1)] |
Ordered dictionary
Reserves the order in which the elements were inserted
1 2 3 4 |
import collections dict = {'A':3, 'C':1, 'B':2} # Python 2 syntax print(collections.OrderedDict(dict.iteritems())) |
This will print…
1 |
OrderedDict([('A', 3), ('C', 1), ('B', 2)]) |
Thanks for visiting.
Questions ? feedback ? please use the comments section below