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

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!