dict.keys() / .values()
Python · Dictionaries
Theory
.keys() returns all the keys of a dictionary and .values() returns all the values, both in insertion order. With employee = {'name': 'Asha', 'salary': 65000}, list(employee.keys()) is ['name', 'salary'] and list(employee.values()) is ['Asha', 65000]. They do not return lists; they return view objects (dict_keys and dict_values) that look into the dict live, so if you add a key later, an existing view shows it too. Wrap a view in list() when you need indexing or a snapshot.
Views are cheap: no copying happens, and you can loop over them, use len() and test membership. Key views even behave like sets, so employee.keys() & other.keys() finds common keys. Note that looping over the dict itself already gives keys (for k in employee), so .keys() is often unnecessary. Searching values with x in employee.values() is a linear scan, O(n), unlike the hashed key check x in employee, which is O(1) on average.
Why we use it
You often need just one side of a dictionary: all column names, all scores to average, every product ID. keys() and values() hand you exactly that side without manual loops.
When to use it
Use values() to aggregate (sum(d.values()), max(d.values())) and keys() for set-like comparisons between dicts. Just loop over the dict for keys. Use items() when you need both key and value together.
How it works
- Call employee.keys()
- Python creates a live view onto the dict (no copy)
- Need a real list (indexing, snapshot)? Yes: Wrap it: list(employee.keys()). No: Loop over the view directly.
- Iterate in insertion order
- Output: ['name', 'salary'] and ['Asha', 65000]
Syntax
dict.keys()
dict.values()Example
employee = {'name': 'Asha', 'salary': 65000}
print(list(employee.keys()))
print(list(employee.values()))Key points
- Both return view objects; wrap in list() to get an actual list
- Views are live: they reflect later changes to the dict
- Iterate directly over a dict to get its keys: for k in employee
- x in d.values() scans O(n); x in d checks keys in O(1)
- keys() supports set operations: d1.keys() & d2.keys()