Python: How to Return a dictionary keys as a list


Let's take a look at some of the possible ways in Python Programming to return a dictionary (dict) keys as a list.


Example 1: Using the dict.keys() method

locations = {'USA': 'New York', 'Japan': 'Tokyo', 'India': 'Mumbai'}

country_list = list(locations.keys())

print(country_list)

Output:
['USA', 'Japan', 'India']

Read more on documentation:


dict.keys(): return's a new view of the dictionary’s keys

https://docs.python.org/3.11/library/stdtypes.html#dict.keys

Example 2: Using dictionary unpacking

locations = {'USA': 'New York', 'Japan': 'Tokyo', 'India': 'Mumbai'}

country_list = [*locations]

print(country_list)

Read more on documentation:

PEP 448 – Additional Unpacking Generalizations: https://peps.python.org/pep-0448/

Example 3: Using list comprehension

locations = {'USA': 'New York', 'Japan': 'Tokyo', 'India': 'Mumbai'}

country_list = [country for country in locations]

print(country_list)
Python- How to Return a dictionary keys as a list

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap