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 typePython 2 syntaxPython 3 syntax
Sorted dictionary keyssorted(dict)sorted(dict)
Sorted dictionary valuessorted(dict.itervalues())sorted(dict.values())
Sorted dictionary items by valuesorted(dict.iteritems(), key = lambda x : x[1])sorted(dict.items(), key = lambda x : x[1])
Sorting in reverse ordersorted(dict, reverse=True)sorted(dict, reverse=True)
Ordered dictionarycollections.OrderedDict(dict.iteritems())collections.OrderedDict(dict.items())

Let us now take some examples…

Sorted dictionary keys

This will print…

Sorted dictionary values

This will print…

Sorted dictionary items by value

This will print…

Sorting in reverse order

This will print…

Ordered dictionary

Reserves the order in which the elements were inserted

This will print…

Thanks for visiting.
Questions ? feedback ? please use the comments section below

Add a Comment

Your email address will not be published. Required fields are marked *