Skip to content
  • YouTube
  • FaceBook
  • Twitter
  • Instagram

Data Analytics Ireland

Data Analytics and Video Tutorials

  • Home
  • Contact
  • About Us
    • Latest
    • Write for us
    • Learn more information about our website
  • Useful Links
  • Glossary
  • All Categories
  • Faq
  • Livestream
  • Toggle search form
  • How to count the no of rows and columns in a CSV file CSV
  • How To Fix TypeError: unhashable type ‘slice’ python dictionaries
  • Python Overview Interview Questions automation
  • how to create and drop a table in SQL SQL
  • How to create a combobox in tkinter Python
  • Create a HTML Table From Python Using Javascript Javascript
  • How To Validate Cell Values In Excel Python
  • What are measures in Tableau? data visualisation

How to sort a Python Dictionary

Posted on November 9, 2022January 28, 2023 By admin No Comments on How to sort a Python Dictionary

Estimated reading time: 3 minutes

In our Python Overview Interview Questions we started off the process of trying to prepare you how to answer any questions that may come up in an interview scenario.

We then moved on to show how to discuss Python Dictionary Interview Questions and what may come up.

One of the questions that you may be asked is how to deal with sorting a python dictionary using a key.

Some of the ways that you may want to sort are as follows, read on for code examples:

Python Dictionary Interview Questions

How to use the sorted and Items Method in Python

In the below code, we have created an empty dictionary and then appened in three key-value pairs.

The first print statement just prints out the dictionary in its unordered fashion.

The second print statement does two things:

  1. It, first of all, sorts the empty_dict1 items in order
  2. Then it goes and creates them in a dictionary.

The reason we have to do step two is that the sorted() function returns a sorted list, as a result, it is not in a dictionary format.

empty_dict1 = {}

empty_dict1['Key2'] = '2'
empty_dict1['Key1'] = '1'
empty_dict1['Key3'] = '3'
print("Your unsorted by key dictionary is:",empty_dict1)
print("Your sorted by key dictionary is:",dict(sorted(empty_dict1.items())))

Result:
Your unsorted by key dictionary is: {'Key2': '2', 'Key1': '1', 'Key3': '3'}
Your sorted by key dictionary is: {'Key1': '1', 'Key2': '2', 'Key3': '3'}

How to use List comprehension to sort a Python dictionary

As a follow on to the above, we could also just iterate over the dictionary using list comprehensions.

The below creates a variable called d. This is set equal to the output of the list comprehension.

Note that inside the {} brackets you have a:b, this purely creates two sets of values that will be used as the output to generate the dictionary.

You will also see that this creates index values, starting at 0, not the actual values we want.

As a result, we just drop these index values and replace them with the values we want using the pop() method.

The final two print statements show the before and after of sorting the dictionary!

d = {a:b for a, b in enumerate(empty_dict1.values())}
print(d)
d["Key2"] = d.pop(0) #replaces 0 with Key2
d["Key1"] = d.pop(1) #replaces 1 with Key1
d["Key3"] = d.pop(2) #replaces 2 with Key3
print(d)
print(dict(sorted(d.items())))

Result:
{0: '2', 1: '1', 2: '3'}
{'Key2': '2', 'Key1': '1', 'Key3': '3'}
{'Key1': '1', 'Key2': '2', 'Key3': '3'}

How to use a loop to sort a Python dictionary

d={0:2, 1: 1, 2: 3}
dict_loop={}
for i in sorted(d):
   dict_loop[i]=d[i]
print("")
print("Sorted dictionary using a loop",dict_loop)
Python, python dictionaries, Python Functions, python interview questions Tags:Learn python, Python, python dictionaries, python sorting

Post navigation

Previous Post: How To Add Values to a Python Dictionary
Next Post: How to delete a key from a Python dictionary

Related Posts

  • How Would You Change The Name Of a Key in a Python Dictionary Python
  • Python tutorial: Pandas groupby ( Video 1) Python
  • Tkinter python tutorial Python
  • How To Fix TypeError: unhashable type ‘slice’ python dictionaries
  • How to change the headers on a CSV file CSV
  • How to create a class in Python class

Leave a Reply Cancel reply

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

Select your language!

  • English
  • Español
  • Português
  • Français
  • Italiano
  • How to show percentage differences between files in Python CSV
  • How to Automate Testing With Python | unittest automation
  • how to update records in SQL CRUD
  • How to add a date when a record is created SQL
  • How to count the no of rows and columns in a CSV file CSV
  • TypeError: ‘float’ object is not callable Python
  • data cleansing in a business environment Articles
  • Free ways to Extract Data from Files Livestream

Copyright © 2023 Data Analytics Ireland.

Powered by PressBook Premium theme

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT