A dictionary stores data as key-value pairs, such as {"name": "Jessa", "age": 28}. Dictionaries have 11 built-in methods for reading values safely, looping over keys and values, adding and updating entries, removing items, and copying.
In this tutorial, you’ll learn every dictionary method with examples, the dictionary merge operators, how view objects behave, and the patterns experienced Python developers use every day.
Key terms used in this article:
- Key: The unique label used to look up a value. Keys must be hashable (immutable), such as strings, numbers, or tuples.
- Value: The data stored under a key. Values can be any type.
- Item: A key-value pair.
- View object: A live, read-only window into a dictionary’s keys, values, or items. It updates when the dictionary changes.
- Insertion order: Since Python 3.7, dictionaries remember the order in which keys were added.
Table of contents
- Dictionary methods at a glance
- Reading values
- Looping with keys(), values(), and items()
- Adding and updating items
- Removing items
- Copying dictionaries
- Creating dictionaries with fromkeys()
- Other useful dictionary operations
- Related tools: defaultdict and Counter
- Real-world example: word frequency counter with plain methods
- Common mistakes
- Practice exercises
- Summary
Dictionary methods at a glance
| Method | Description |
|---|---|
get(key, default=None) | Returns the value for a key, or a default if the key is missing |
keys() | Returns a view of all keys |
values() | Returns a view of all values |
items() | Returns a view of all (key, value) pairs |
update(other) | Adds or overwrites items from another dictionary or iterable of pairs |
setdefault(key, default=None) | Returns the value for a key, and inserts the default first if the key is missing |
pop(key, default) | Removes a key and returns its value |
popitem() | Removes and returns the last inserted (key, value) pair |
clear() | Removes all items |
copy() | Returns a shallow copy |
fromkeys(iterable, value=None) | Class method that creates a new dictionary from a list of keys |
The examples below use this dictionary:
Output:
{'name': 'Jessa', 'role': 'Developer', 'salary': 7500}
3
Reading values
Square brackets vs. get()
dict[key] raises a KeyError when the key is missing. get() returns None or a default value instead:
Output:
Jessa Developer None 0 KeyError: 'bonus'
Use square brackets when the key must exist (a missing key is a bug). Use get() when a missing key is normal.
Note that get() doesn’t add the key to the dictionary. Also, if the key exists with the value None, get() returns None, not the default.
Checking whether a key exists
Use in to check keys. It doesn’t search values:
Output:
True True False True
Looping with keys(), values(), and items()
keys()
Output:
dict_keys(['name', 'role', 'salary']) name role salary
Looping over the dictionary itself also gives you the keys, so for key in employee: is the usual shortcut.
values()
Output:
dict_values([1.2, 0.5, 3.0]) 4.7 3.0
items()
items() returns (key, value) tuples. Unpack them in the for loop:
Output:
apple $1.20 banana $0.50 cherry $3.00
View objects are live
keys(), values(), and items() return views, not copies. A view always reflects the current contents of the dictionary:
Output:
dict_keys(['pens', 'books']) dict_keys(['pens', 'books', 'lamps']) ['pens', 'books', 'lamps']
Key views behave like sets, so you can compare the keys of two dictionaries directly. The results are sets, which are unordered, so they’re sorted here for a predictable output:
Output:
['y', 'z'] ['x'] ['w', 'x', 'y', 'z']
You can’t add or remove keys while looping over a dictionary. Doing so raises RuntimeError: dictionary changed size during iteration. Loop over list(d) instead.
Adding and updating items
Assigning with square brackets
Output:
{'name': 'Jessa Doe', 'role': 'Developer'}
update()
update() adds or overwrites several items at once. It accepts another dictionary, an iterable of key-value pairs, or keyword arguments:
Output:
{'name': 'Jessa', 'salary': 8000, 'city': 'London'}
{'name': 'Jessa', 'salary': 8000, 'city': 'London', 'team': 'Backend'}
{'name': 'Jessa', 'salary': 8000, 'city': 'London', 'team': 'Backend', 'level': 3, 'remote': True}
The merge operators | and |= (Python 3.9+)
| merges two dictionaries into a new one. |= updates a dictionary in place, like update(). When a key exists in both, the value from the right side wins:
Output:
{'theme': 'dark', 'font_size': 14, 'autosave': True}
{'theme': 'light', 'font_size': 12, 'autosave': True}
{'theme': 'light', 'font_size': 12, 'autosave': False}
In older versions, use {**defaults, **user_prefs} to merge into a new dictionary.
setdefault()
setdefault(key, default) returns the value of key if it exists. If it doesn’t, it inserts the key with the default value and returns that value:
Output:
localhost
8080
{'host': 'localhost', 'port': 8080}
setdefault() is handy for grouping items into lists:
Output:
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
For the same job, collections.defaultdict(list) is often cleaner. See the section on related tools below.
Removing items
pop()
pop(key) removes the key and returns its value. Pass a default to avoid a KeyError when the key might be missing:
Output:
7500 {'name': 'Jessa', 'role': 'Developer'}
not found
KeyError: 'bonus'
popitem()
popitem() removes and returns the last inserted item as a tuple (last in, first out). It raises KeyError on an empty dictionary:
Output:
('third', 3)
('second', 2)
{'first': 1}
del and clear()
Output:
{'b': 2, 'c': 3}
{}
| You want to | Use |
|---|---|
| Remove a key and get its value | pop(key) |
| Remove a key that might be missing | pop(key, None) |
| Remove a key without needing the value | del d[key] |
| Remove the most recently added item | popitem() |
| Remove everything | clear() |
Copying dictionaries
copy()
b = a doesn’t copy a dictionary. Both names refer to the same object. Use copy() (or dict(a)) for a new dictionary:
Output:
Kelly Jessa
copy() is shallow: nested lists and dictionaries are still shared. Use copy.deepcopy() for a fully independent copy:
Output:
['Python', 'SQL', 'Docker'] ['Python', 'SQL']
Creating dictionaries with fromkeys()
dict.fromkeys(keys, value) creates a new dictionary where every key gets the same value:
Output:
{'name': None, 'email': None, 'phone': None}
{'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
Watch out: If the value is mutable, such as a list, every key shares the same list. Use a dictionary comprehension to give each key its own list: {key: [] for key in fields}.
Output:
{'a': [1], 'b': [1]}
{'a': [1], 'b': []}
dict.fromkeys() is also a quick way to remove duplicates from a list while keeping the order: list(dict.fromkeys(items)).
Other useful dictionary operations
Output:
3
['Emma', 'Jessa', 'Kelly']
[('Emma', 79), ('Jessa', 88), ('Kelly', 95)]
Kelly
{'x': 1, 'y': 2}
{88: 'Jessa', 95: 'Kelly', 79: 'Emma'}
['Emma', 'Kelly', 'Jessa']
Related tools: defaultdict and Counter
The collections module has two dictionary subclasses that remove a lot of boilerplate.
defaultdict creates a default value automatically when you access a missing key:
Output:
{'Jessa': ['pen', 'lamp'], 'Kelly': ['book']}
Counter counts hashable items:
Output:
[('the', 3), ('quick', 1)]
Real-world example: word frequency counter with plain methods
Output:
is 3 python 3 fun 2 learning 1 powerful 1
frequency.get(word, 0) + 1 is the classic counting pattern: start at 0 if the word is new, otherwise add one to the current count.
Common mistakes
- Using
d[key]for optional keys. Used.get(key, default)to avoidKeyError. - Changing a dictionary while looping over it. Loop over
list(d)or build a new dictionary. - Expecting
into search values. It checks keys. Usevalue in d.values(). - Using mutable keys. Lists can’t be keys (
TypeError: unhashable type: 'list'). Use tuples. - Sharing a mutable default with
fromkeys(). Use a dictionary comprehension instead. - Assuming
b = acopies the dictionary. Usea.copy()orcopy.deepcopy(a).
Output:
{'b': 2}
Error: unhashable type: 'list'
{('x', 'y'): 1}
Practice exercises
Exercise 1: Merge two dictionaries, adding the values of keys that appear in both.
Output:
{'apples': 8, 'pears': 2, 'plums': 4}
Exercise 2: Invert a dictionary of student grades so that each grade maps to a list of students.
Output:
{'A': ['Jessa', 'Emma'], 'B': ['Kelly'], 'C': ['Brad']}
Exercise 3: Keep only the items whose value is above a threshold.
Output:
{'laptop': 1200, 'monitor': 300}
Summary
- Dictionaries have 11 methods:
get(),keys(),values(),items(),update(),setdefault(),pop(),popitem(),clear(),copy(), andfromkeys(). - Use
get()to read optional keys safely andinto check whether a key exists. - Loop with
items()to get keys and values together.keys(),values(), anditems()return live views. - Add or change items with
d[key] = value,update(), or the|and|=operators. - Remove items with
pop(),popitem(),del, orclear(). copy()is shallow. Usecopy.deepcopy()for nested data, and avoid mutable defaults withfromkeys().
Also, See:

Leave a Reply