Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Sorted Nested Keys in Dictionary
Next article icon

Python | Sort dictionary keys to list

Last Updated : 05 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, we wish to flatten the dictionary into list, the simple flattening is relatively easier, but when we wish to align keys and values in sorted way, i.e sorted by value, then it becomes quite a complex problem. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using sum() + sorted() + items() + lambda The combination of above functions can be used to perform this particular task. In this, firstly we sort the dictionary by keys for desired order using sorted(), then keys and values are extracted by items() functions that are returned as pair by lambda function. The sum function does the task of populating the tuple. 

Python3




# Python3 code to demonstrate working of
# Sort dictionary keys to list
# Using sum() + sorted() + items() + lambda
 
# initializing dictionary
test_dict = {'Geeks' : 2, 'for' : 1, 'CS' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Using sum() + sorted() + items() + lambda
# Sort dictionary keys to list
res = list(sum(sorted(test_dict.items(), key = lambda x:x[1]), ()))
 
# printing result
print("List after conversion from dictionary : " + str(res))
 
 

Time Complexity: O(n*log n)

Space Complexity: O(n)

Output : 
The original dictionary is : {'Geeks': 2, 'for': 1, 'CS': 3} List after conversion from dictionary : ['for', 1, 'Geeks', 2, 'CS', 3]

  Method #2 : Using chain() + sorted() + items() + lambda This method is also similar to above method, the only difference is that the construction of the final list is done by the chain method which reduces the intermediate step of conversion to tuple and does the whole task in linear time. 

Python3




# Python3 code to demonstrate working of
# Sort dictionary keys to list
# Using chain() + sorted() + items() + lambda
from itertools import chain
 
# initializing dictionary
test_dict = {'Geeks' : 2, 'for' : 1, 'CS' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Using chain() + sorted() + items() + lambda
# Sort dictionary keys to list
res = list(chain(*sorted(test_dict.items(), key = lambda x: x[1])))
 
# printing result
print("List after conversion from dictionary : " + str(res))
 
 

Time Complexity: O(n*log n)

Space Complexity: O(n)

Output : 
The original dictionary is : {'Geeks': 2, 'for': 1, 'CS': 3} List after conversion from dictionary : ['for', 1, 'Geeks', 2, 'CS', 3]

Method #3 : Using keys(),values(),sort(),index() methods

Approach

  1. Extract keys, values using keys() and values() methods
  2. Sort the values list
  3. Append the keys and sorted values accordingly to output list
  4. Display output list

Python3




# Python3 code to demonstrate working of
# Sort dictionary keys to list
 
# initializing dictionary
test_dict = {'Geeks': 2, 'for': 1, 'CS': 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
res = []
x = list(test_dict.keys())
y = list(test_dict.values())
z = []
z.extend(y)
z.sort()
for i in z:
    res.append(x[y.index(i)])
    res.append(i)
# printing result
print("List after conversion from dictionary : " + str(res))
 
 
Output
The original dictionary is : {'Geeks': 2, 'for': 1, 'CS': 3} List after conversion from dictionary : ['for', 1, 'Geeks', 2, 'CS', 3]

Time Complexity : O(N logN)

Auxiliary Space : O(N)

Method #5: Using map(), zip() and sorted()

Use the zip() function to create a list of tuples, where each tuple contains a key-value pair from the dictionary.
Use the map() function to create a list of tuples, where each tuple contains a key and its corresponding value.
Use the sorted() function to sort the list of tuples by the keys.
Use the zip() function again to create a list of tuples, where each tuple contains a key and its corresponding value.
Use a list comprehension to flatten the list of tuples into a single list.
Return the flattened list.

Python3




# Python3 code to demonstrate working of
# Sort dictionary keys to list
 
# initializing dictionary
test_dict = {'Geeks': 2, 'for': 1, 'CS': 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# sorting dictionary keys to list using map(), zip() and sorted()
res = [elem for tup in sorted(zip(test_dict.keys(), test_dict.values())) for elem in tup]
 
# printing result
print("List after conversion from dictionary : " + str(res))
 
 
Output
The original dictionary is : {'Geeks': 2, 'for': 1, 'CS': 3} List after conversion from dictionary : ['CS', 3, 'Geeks', 2, 'for', 1]

Time complexity: O(n log n) for sorting the keys and O(n) for iterating over the dictionary and creating the list of tuples, so overall O(n log n).

Auxiliary space: O(n) for the res list



Next Article
Python - Sorted Nested Keys in Dictionary
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
Practice Tags :
  • python

Similar Reads

  • Python - Sort Dictionary key and values List
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Let's discuss certain way in which this task can be performed. Input : test_d
    6 min read
  • Python | Sort nested dictionary by key
    Sorting has quite vivid applications and sometimes, we might come up with a problem in which we need to sort the nested dictionary by the nested key. This type of application is popular in web development as JSON format is quite popular. Let's discuss certain ways in which this can be performed. Met
    4 min read
  • Python - Sorted Nested Keys in Dictionary
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the keys of nested dictionaries and render them in sorted order. This kind of application can occur in domains in which we work with data. Lets discuss certain ways in which this task can be perf
    4 min read
  • Python - Sort List by Dictionary values
    Sometimes while working with a Python dictionary, we can have problems in which we need to perform a sort of list according to the corresponding value in the dictionary. This can have applications in many domains, including data and web development. Let's discuss certain ways in which this task can
    3 min read
  • Python - Keys with shortest length lists in dictionary
    Sometimes, while working with Python lists, we can have problem in which we need to return the keys which have minimum lengths of lists as values. This can have application in domains in which we work with data. Lets discuss certain ways in which this task can be performed. Method #1: Using len() +
    4 min read
  • Python program to sort Dictionary by Key Lengths
    Given Dictionary, sort by its key lengths. Input : test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3} Output : {'is': 1, 'Gfg': 4, 'for': 3, 'best': 0, 'geeks': 3} Explanation : 2 < 3 = 3 < 4 < 5, are sorted lengths in order. Input : test_dict = {"Gfg" : 4, "for" : 3, "ge
    4 min read
  • Python - Sort dictionary by Tuple Key Product
    Given dictionary with tuple keys, sort dictionary items by tuple product of keys. Input : test_dict = {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12} Output : {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12} Explanation : 6 < 18 < 32 < 40, key products hence retains order. Input : test_d
    5 min read
  • Python | Sort dictionary by value list length
    While working with Python, one might come to a problem in which one needs to perform a sort on dictionary list value length. This can be typically in case of scoring or any type of count algorithm. Let's discuss a method by which this task can be performed. Method 1: Using sorted() + join() + lambda
    4 min read
  • How to Print Dictionary Keys in Python
    We are given a dictionary and our task is to print its keys, this can be helpful when we want to access or display only the key part of each key-value pair. For example, if we have a dictionary like this: {'gfg': 1, 'is': 2, 'best': 3} then the output will be ['gfg', 'is', 'best']. Below, are the me
    2 min read
  • Dictionary keys as a list in Python
    In Python, we will encounter some situations where we need to extract the keys from a dictionary as a list. In this article, we will explore various easy and efficient methods to achieve this. Using list() The simplest and most efficient way to convert dictionary keys to lists is by using a built-in
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences