In Python, items(), keys(), and values() are dictionary methods that return views of a dictionary’s key-value pairs, keys, and values respectively. For example, d = {'a': 1, 'b': 2}; d.items() gives dict_items([('a', 1), ('b', 2)]), d.keys() gives dict_keys(['a', 'b']), and d.values() gives dict_values([1, 2]).
What Are Dictionary Views?
When you call items(), keys(), or values() on a dictionary, Python returns a view object, not a list. A view is a dynamic, read-only projection of the dictionary’s current contents. If you modify the dictionary after creating a view, the view reflects the changes immediately.
d = {'x': 10}
v = d.keys()
print(v) # dict_keys(['x'])
d['y'] = 20
print(v) # dict_keys(['x', 'y'])
Views also support set-like operations for keys() and items() (e.g., union, intersection), which can be handy for comparing dictionaries. However, values() views do not support set operations because values can be duplicated.
How to Use items(), keys(), and values()
These methods are commonly used in loops and for membership testing. Here are the typical patterns:
- Iterate over key-value pairs:
for k, v in d.items(): - Check if a key exists:
if 'key' in d.keys():— but note thatif 'key' in d:is more efficient and idiomatic. - Get all values as a list:
list(d.values()) - Get all keys as a list:
list(d.keys())
If you need a list of tuples of key-value pairs, use list(d.items()). This is useful when you want to sort or pass the pairs to a function that expects a list.
Converting Views to Lists or Other Types
Views are not subscriptable (you cannot do d.keys()[0]). To access an element by index, convert the view to a list first:
keys_list = list(d.keys())
first_key = keys_list[0]
Alternatively, you can use next(iter(d.keys())) to get the first key without creating a full list. When converting to a list, note that the order of items is the insertion order (since Python 3.7, dictionaries preserve insertion order).
Performance and Memory Considerations
Views are lightweight because they do not copy the data. Converting to a list creates a new list and copies references, which takes O(n) time and memory. For large dictionaries, avoid unnecessary conversions. Iterating over a view is as fast as iterating over the dictionary itself.
One common mistake is to call list(d.keys()) just to check membership. Instead, use key in d directly, which is O(1) on average. Similarly, to check if a value exists, use value in d.values() — this is O(n), but it avoids creating a list.
Differences Between Python 2 and Python 3
In Python 2, items(), keys(), and values() returned lists, and there were separate methods iteritems(), iterkeys(), and itervalues() that returned iterators. In Python 3, the list-returning versions were removed, and the methods now return views. If you are maintaining legacy Python 2 code, you must update it to Python 3 syntax. For example, d.iteritems() becomes d.items().
Common Problems and Misconceptions
Problem: Modifying a dictionary while iterating over its items. If you add or remove items during iteration, you may get a RuntimeError: dictionary changed size during iteration. To avoid this, iterate over a copy: for k in list(d.keys()): or collect changes and apply them after the loop.
Misconception: d.keys() returns a list. It returns a view. If you try to index it directly, you’ll get a TypeError. Always convert to a list if you need indexing.
Misconception: items() returns a list of tuples. It returns a view of tuples. The view is iterable, so you can unpack in a for loop, but you cannot slice it.
Alternatives to items(), keys(), and values()
For some use cases, other approaches may be more appropriate:
- Using
dict.get(): Instead of checking if a key exists and then retrieving it, used.get(key, default)to avoid aKeyError. - Using
collections.ChainMap: To combine multiple dictionaries and view their keys/values as a single mapping, useChainMap. - Using
defaultdict: When you need to handle missing keys automatically,collections.defaultdictprovides a default value. - Using
dict.setdefault(): To set a key only if it doesn’t exist,d.setdefault(key, default)is a concise alternative.
Frequently Asked Questions
Q: What is the difference between d.items() and list(d.items())?
A: d.items() returns a view that reflects the dictionary’s current state and does not copy data. list(d.items()) creates a new list of tuples, which is a snapshot. If the dictionary changes, the view changes, but the list does not.
Q: Can I use d.keys() to check if a key exists?
A: Yes, but it’s not recommended. The idiomatic way is if key in d:, which is faster because it checks the dictionary’s internal hash table directly, whereas key in d.keys() also works but adds a method call overhead.
Q: How do I get the first key of a dictionary?
A: Since Python 3.7, dictionaries maintain insertion order, so you can use next(iter(d)) to get the first key without converting to a list. For older Python versions, use list(d.keys())[0] (but note that order was not guaranteed before 3.7).
Q: Why does d.values() not support set operations?
A: Set operations require unique elements. Dictionary values can be duplicated, so values() views do not implement set-like methods. Keys, on the other hand, are unique by definition, so keys() and items() (where each tuple is unique) support set operations.
Q: Can I modify a dictionary while iterating over d.items()?
A: You can modify existing values, but you cannot add or remove keys. If you try to add or remove, Python raises a RuntimeError. To safely change the size, iterate over a list copy: for k in list(d.keys()):.
Related
- Generate Uniform Random Numbers in Python
- Free Excel Mileage Log: How to Build One
- Data Entry Clerk: Job, Skills & Salary
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Data Validation: Pull Choices From a ListYes. In Microsoft Excel for Microsoft 365 on Windows, select the cells that need a drop-down, choose Data…
- Google Sheets Data Validation for Time ValuesTo validate time entries in Google Sheets, select the cells, choose Data > Data validation > Add rule,…
- Parts Inventory Spreadsheet: What to Track and HowA parts inventory spreadsheet is a workbook for recording what parts you have, where they are, what they…
- Excel MAXIFS: Find the Highest Value for Each DateYes. In Excel, use MAXIFS to return the largest value from rows whose date matches a chosen date.…
- Excel: Hide Duplicates Based on One Column in a ListTo hide entire rows when a value repeats in one column, add a helper column, mark the first…
- Sign Out Shortcut Windows: 5 Fast WaysThe fastest way to sign out of Windows 10 or Windows 11 is to press Ctrl + Alt…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.