0
0
PythonHow-ToBeginner · 3 min read

How to Get All Keys of Dictionary in Python Easily

To get all keys of a dictionary in Python, use the dict.keys() method which returns a view of keys. You can convert this view to a list with list(dict.keys()) if you need a list of keys.
📐

Syntax

The syntax to get all keys from a dictionary is simple:

  • dict.keys(): Returns a view object of all keys.
  • list(dict.keys()): Converts the keys view into a list.
python
dictionary = {'a': 1, 'b': 2, 'c': 3}
keys_view = dictionary.keys()
keys_list = list(dictionary.keys())
💻

Example

This example shows how to get all keys from a dictionary and print them as a list.

python
my_dict = {'name': 'Alice', 'age': 30, 'city': 'Paris'}
keys = my_dict.keys()
print(keys)  # Shows keys view object
keys_list = list(keys)
print(keys_list)  # Shows list of keys
Output
dict_keys(['name', 'age', 'city']) ['name', 'age', 'city']
⚠️

Common Pitfalls

One common mistake is trying to use dict.keys() as a list directly without converting it. The keys view looks like a list but is not one, so some list operations won't work.

Also, modifying the dictionary while iterating over dict.keys() can cause errors.

python
my_dict = {'x': 10, 'y': 20}
keys = my_dict.keys()
# Wrong: keys.append('z')  # AttributeError: 'dict_keys' object has no attribute 'append'

# Correct way:
keys_list = list(keys)
keys_list.append('z')
print(keys_list)
Output
['x', 'y', 'z']
📊

Quick Reference

Summary tips to get dictionary keys:

  • Use dict.keys() to get keys view.
  • Convert to list with list(dict.keys()) if needed.
  • Do not modify dictionary while iterating keys.

Key Takeaways

Use dict.keys() to get all keys from a dictionary as a view.
Convert keys view to a list with list(dict.keys()) for list operations.
Do not treat dict.keys() as a list directly; it is a view object.
Avoid changing the dictionary while iterating over its keys.