Python | Get dictionary keys as a list

Python | Get dictionary keys as a list

To get the keys of a dictionary as a list in Python, you can use the list() function in combination with the dictionary's keys() method.

Here's a quick example:

# Sample dictionary data = { 'name': 'John', 'age': 25, 'city': 'New York' } # Get dictionary keys as a list keys_list = list(data.keys()) print(keys_list) 

Output:

['name', 'age', 'city'] 

In this example, the keys() method retrieves the keys of the dictionary, and the list() function converts them into a list. If you're using Python 2.x, the keys() method of a dictionary would directly return a list, but in Python 3.x, it returns a dictionary view, which is why you need to explicitly convert it to a list.


More Tags

wizard concurrent-collections android-viewpager2 spaces replaykit outliers zurb-foundation-6 bit fortify k6

More Programming Guides

Other Guides

More Programming Examples