Master Code
On The Go

Learn. Practice. Build.

Home › Code Snippets › Python › Reference › keys()

Python Reference

dict.keys()

Return a view of all keys in a dictionary. Dynamic and iterable.

Last updated: October 2026

Definition: dict.keys() returns a view object containing all the keys in the dictionary. The view is dynamic — it reflects changes made to the dict. It is iterable and supports set operations.

🎬 Live Example

Five common keys patterns. Click any button to see the output.

Input:

                
Output:

            

💡 keys() returns a view, not a list. It reflects live changes to the dict.

📝

Basic Syntax

dict.keys()

# No arguments
# Returns: dict_keys view object
# Dynamic — reflects dict changes
# Iterable and set-like
1

Basic Usage

d = {"name": "Alice", "age": 30}
d.keys()
# dict_keys(['name', 'age'])

# Iterate directly
for key in d.keys():
    print(key)
# name
# age
2

Convert to List

d = {"a": 1, "b": 2}

list(d.keys())
# ['a', 'b']

# Same as:
list(d)
# ['a', 'b']

# Sort keys
sorted(d.keys())
# ['a', 'b']

Pro tip: list(d) and list(d.keys()) produce identical results. Iterating a dict directly yields keys.

3

Dynamic View

d = {"a": 1}
keys = d.keys()

d["b"] = 2
list(keys)
# ['a', 'b']  ← reflects new key

del d["a"]
list(keys)
# ['b']

Note: Views are live. Don't modify a dict while iterating its view — use list(d.keys()) to snapshot first.

4

Set Operations

d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}

d1.keys() & d2.keys()   # {'b'} — intersection
d1.keys() | d2.keys()   # {'a', 'b', 'c'} — union
d1.keys() - d2.keys()   # {'a'} — difference
5

Real-World: Check Required Fields

required = {"name", "email"}
user = {"name": "Alice", "email": "a@x.com", "age": 30}

if required.issubset(user.keys()):
    print("All required fields present")

# Or find missing fields
missing = required - user.keys()
# set()

🎯 keys vs values vs items

Method Returns Use when
keysKeys viewYou need only keys
valuesValues viewYou need only values
items(key, value) pairsYou need both together

⚠️ Common Mistakes

❓ Frequently Asked Questions

What does dict.keys() do in Python?

dict.keys() returns a view object containing all the keys in the dictionary. The view is dynamic — it reflects changes made to the dict.

Is dict.keys() a list?

No. In Python 3, it returns a view object, not a list. Wrap it in list() if you need an actual list: list(d.keys()).

Can I iterate over dict.keys()?

Yes. The keys view is iterable. You can loop directly: for key in d.keys(). You can also omit .keys() and iterate the dict directly.

What is the difference between keys() and values()?

keys() returns the dictionary keys. values() returns the dictionary values. items() returns both as (key, value) tuples.

Does dict.keys() reflect changes to the dict?

Yes. The view is dynamic. If you add or remove keys from the dict, the view updates automatically.

🎯 What's Next?

← All Python Reference