Python Dictionary Methods โ Complete Guide with Examples
A complete beginner-friendly guide to every built-in Python dictionary method โ get, keys, values, items, update, pop, popitem, setdefault, fromkeys, copy, clear โ with real code examples, comparison tables, and interview questions.
Last Updated
April 2026
Read Time
21 min
Level
Beginner
What is a Python Dictionary?
A Python dictionary is a mutable, key-value paired collection, created using curly braces {} with key: value pairs, or the dict() constructor. Instead of accessing elements by numeric position like a list, you access dictionary values using a unique key โ making dictionaries the natural choice whenever data is naturally described by a label rather than a position.
Since Python 3.7, dictionaries officially preserve insertion order as a guaranteed language feature โ before that, in Python 3.6 it was an implementation detail of CPython, and in Python 3.5 and earlier, dictionaries had no guaranteed order at all. In 2026, every dictionary you create will iterate in the exact order its keys were first inserted.
Just like sets, dictionaries are built on a hash table internally โ which is why keys must be hashable (immutable types like strings, numbers, or tuples), and why looking up a value by its key is extremely fast, close to constant time regardless of how many entries the dictionary holds.
student = {"name": "Priya", "age": 21, "course": "Python"}
print(student)
print(type(student))Output
{'name': 'Priya', 'age': 21, 'course': 'Python'} <class 'dict'>Creating and Accessing Dictionaries
Dictionaries can be created using curly brace literals, the dict() constructor, or by converting a list of key-value pairs. Accessing a value uses square bracket notation with the key, similar to a list โ except the 'index' is a key, not a number.
using_dict = dict(name="Rahul", age=25)
print(using_dict)
from_pairs = dict([("a", 1), ("b", 2)])
print(from_pairs)
student = {"name": "Priya", "age": 21}
print(student["name"])Output
{'name': 'Rahul', 'age': 25} {'a': 1, 'b': 2} PriyaAccessing a missing key with square brackets raises a KeyError โ this is the single biggest source of dictionary-related crashes for beginners, and it's exactly what the get() method exists to solve.
student = {"name": "Priya"}
print(student["grade"])Output
KeyError: 'grade'Complete List of Python Dictionary Methods
Python provides 11 core built-in dictionary methods, covering safe access, bulk retrieval of keys/values/pairs, modification, removal, and creation shortcuts. Here is the complete overview:
Returns the value for a key, or a default (None by default) if the key doesn't exist โ never raises an error, unlike square bracket access.
Returns a view object displaying all the keys in the dictionary, in insertion order, which stays live-synced with the dictionary.
Returns a view object displaying all the values in the dictionary, in the same order as their corresponding keys.
Returns a view object of (key, value) tuple pairs โ the most common way to iterate over both keys and values together.
Merges another dictionary (or iterable of key-value pairs) into the current one, overwriting values for any matching keys.
Removes a specified key and returns its value. Accepts an optional default to avoid a KeyError if the key is missing.
Removes and returns the last inserted key-value pair as a tuple. Raises a KeyError if the dictionary is empty.
Returns the value for a key if it exists; otherwise inserts the key with a default value and returns that default.
A class method that builds a new dictionary from a sequence of keys, all mapped to the same specified value.
Removes all key-value pairs from the dictionary, leaving it empty.
Returns a shallow copy of the dictionary โ a new, independent dict object with the same key-value pairs.
Safe Access with get()
get(key, default) is the single most important dictionary method for writing crash-free code. It returns the value for key if it exists, or the specified default (which itself defaults to None) if it doesn't โ never raising a KeyError.
student = {"name": "Priya", "age": 21}
print(student.get("name"))
print(student.get("grade"))
print(student.get("grade", "Not Assigned"))Output
Priya None Not AssignedAs a rule: use square brackets (student["name"]) only when you are certain a key exists and its absence would indicate a genuine bug. Use get() whenever the key's presence is uncertain.
Bulk Access โ keys(), values(), and items()
These three methods return special view objects โ not plain lists โ that give you a window into the dictionary's keys, values, and key-value pairs respectively. Crucially, these views stay dynamically synced with the dictionary; if the dictionary changes, the view reflects that change automatically.
student = {"name": "Priya", "age": 21, "course": "Python"}
print(student.keys())
print(student.values())
print(student.items())Output
dict_keys(['name', 'age', 'course']) dict_values(['Priya', 21, 'Python']) dict_items([('name', 'Priya'), ('age', 21), ('course', 'Python')])The most common real-world use of items() is looping over both keys and values simultaneously in a single for loop:
for key, value in student.items():
print(f"{key}: {value}")Output
name: Priya age: 21 course: PythonBecause these views stay live-synced with the dictionary, converting them to a plain list โ using list(student.keys()) โ is necessary whenever you need a static snapshot that won't change if the dictionary is later modified.
Merging Dictionaries with update()
update() merges another dictionary โ or any iterable of key-value pairs โ into the current one. Keys that already exist have their values overwritten; keys that don't exist yet are added.
student = {"name": "Priya", "age": 21}
student.update({"age": 22, "course": "Python"})
print(student)Output
{'name': 'Priya', 'age': 22, 'course': 'Python'}Notice how age was updated from 21 to 22 (an existing key), while course was newly inserted (a key that didn't exist before). update() also accepts keyword arguments directly: student.update(age=23).
Removing Entries โ pop(), popitem(), clear()
๐ค pop() โ Remove by Key
pop(key, default) removes the specified key and returns its value. If the key doesn't exist and no default is given, it raises a KeyError; providing a default avoids that error entirely.
student = {"name": "Priya", "age": 21}
age = student.pop("age")
print(age, student)
grade = student.pop("grade", "N/A")
print(grade)Output
21 {'name': 'Priya'} N/A๐ฒ popitem() โ Remove the Last Inserted Pair
popitem() removes and returns the most recently inserted key-value pair as a tuple. Since Python 3.7, this behavior โ Last-In-First-Out (LIFO) โ is guaranteed by the language, not just an implementation detail.
student = {"name": "Priya", "age": 21, "course": "Python"}
last = student.popitem()
print(last)
print(student)Output
('course', 'Python') {'name': 'Priya', 'age': 21}๐งน clear() โ Empty the Dictionary
student = {"name": "Priya", "age": 21}
student.clear()
print(student)Output
{}setdefault() and fromkeys() โ Convenience Constructors
๐งฉ setdefault() โ Get or Insert in One Step
setdefault(key, default) is a hybrid of get() and assignment: if the key already exists, it simply returns its current value, leaving the dictionary unchanged. If the key doesn't exist, it inserts the key with the given default and then returns that default.
student = {"name": "Priya"}
result1 = student.setdefault("name", "Unknown")
print(result1, student)
result2 = student.setdefault("grade", "Pending")
print(result2, student)Output
Priya {'name': 'Priya'} Pending {'name': 'Priya', 'grade': 'Pending'}setdefault() is especially popular for building dictionaries of lists โ grouping items by category in a single line, without needing to check if key not in dict first.
groups = {}
words = ["apple", "banana", "avocado", "blueberry", "cherry"]
for word in words:
groups.setdefault(word[0], []).append(word)
print(groups)Output
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}๐ญ fromkeys() โ Build a Dict from a Sequence of Keys
dict.fromkeys(sequence, value) is a class method โ called on dict itself, not on an instance โ that creates a new dictionary, using every element of sequence as a key, all mapped to the same value (which defaults to None).
keys = ["a", "b", "c"]
defaults = dict.fromkeys(keys, 0)
print(defaults)
no_value = dict.fromkeys(keys)
print(no_value)Output
{'a': 0, 'b': 0, 'c': 0} {'a': None, 'b': None, 'c': None}Caution: if you pass a mutable object like a list as the value, every key ends up pointing to the same shared list object, not independent copies โ modifying one key's value affects all of them.
shared = dict.fromkeys(["x", "y"], [])
shared["x"].append(1)
print(shared)Output
{'x': [1], 'y': [1]}Copying a Dictionary โ copy() and the Assignment Trap
Exactly like lists and sets, assigning one dictionary variable to another (dict_b = dict_a) does not create a copy โ it creates a second name referencing the same underlying dictionary object.
original = {"a": 1, "b": 2}
reference = original
reference["c"] = 3
print(original)
duplicate = original.copy()
duplicate["d"] = 4
print(original)
print(duplicate)Output
{'a': 1, 'b': 2, 'c': 3} {'a': 1, 'b': 2, 'c': 3} {'a': 1, 'b': 2, 'c': 3, 'd': 4}As with lists, copy() produces a shallow copy โ nested mutable objects inside the dictionary (like a list stored as a value) are still shared between the original and the copy. Use copy.deepcopy() for fully independent nested structures.
How Dictionary Key Lookup Works โ Flowchart
Understanding what happens internally when you access my_dict[key] or call get() clarifies why dictionaries are so fast, and why choosing the right access method avoids unnecessary crashes.
Code Execution Flow โ from source to output
Key insight: whether you use square brackets or get(), Python performs the exact same hash-based lookup internally โ the only difference is what happens at the very last step when the key is missing: a crash versus a graceful fallback.
How Python Dictionaries Work Internally
A Python dictionary is implemented as a hash table, structurally very similar to a set โ except each hash table slot stores a key-value pair instead of just a single value. When you insert a key, Python computes hash(key) and uses that hash to determine exactly where in the underlying array the pair should be stored.
This is exactly why dictionary keys must be hashable โ meaning immutable types like strings, numbers, and tuples of hashable elements โ while dictionary values can be absolutely anything, mutable or immutable, since values are never hashed, only looked up through their associated key's hash.
Since Python 3.7, CPython's dictionary implementation maintains a separate, compact array that records insertion order alongside the hash table used for fast lookup โ this is how dictionaries manage to offer both O(1) average-case key lookup and guaranteed insertion-order iteration simultaneously, a combination that wasn't originally part of the language's design but is now a permanent guarantee.
Dictionary Methods โ Return Values and Behavior
This table summarizes every core dictionary method, its return value, and whether it modifies the dictionary in place โ essential reference for writing efficient, crash-free dictionary code.
Dictionary Comprehension โ Building Dicts in One Line
Just like lists and sets, dictionaries support comprehension syntax โ a concise, readable way to build a new dictionary from an iterable, using the pattern {key_expr: value_expr for item in iterable}.
squares = {x: x**2 for x in range(6)}
print(squares)
prices = {"apple": 100, "banana": 40, "cherry": 300}
discounted = {item: price * 0.9 for item, price in prices.items()}
print(discounted)Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} {'apple': 90.0, 'banana': 36.0, 'cherry': 270.0}Dictionary comprehension also supports conditional filtering, letting you build a new dict containing only entries that satisfy a condition:
scores = {"Alice": 85, "Bob": 45, "Charlie": 90}
passed = {name: score for name, score in scores.items() if score >= 50}
print(passed)Output
{'Alice': 85, 'Charlie': 90}Practice Dictionary Methods โ Live Editor
Try modifying the code below to experiment with dictionary methods. Change the key in get() to one that doesn't exist and observe how it fails gracefully instead of crashing.
Practice This Code โ Live Editor
Dictionary vs List vs Tuple vs Set
Choosing the right collection type depends on whether your data needs positional order, uniqueness, key-based lookup, or mutability. This table breaks down exactly how dictionaries compare to Python's other core collections.
Advantages and Disadvantages of Dictionaries
Real-World Use Cases of Python Dictionaries
- โถ
โ๏ธ Configuration Settings โ Application settings, environment variables, and API configuration are almost universally stored as dictionaries, since each setting is naturally described by a name rather than a position.
- โถ
๐ JSON Data Exchange โ Every JSON object received from a web API is parsed directly into a Python dictionary, making dict methods essential for working with REST APIs and web services.
- โถ
๐๏ธ Caching and Memoization โ Functions that cache expensive computation results typically store them in a dictionary keyed by the function's input arguments, using get() to check for a cached result before recomputing.
- โถ
๐ Counting and Frequency Analysis โ Word frequency counters, vote tallies, and inventory counts commonly use a dictionary combined with setdefault() or get() to accumulate counts per unique key.
- โถ
๐งโ๐ผ Structured Records โ Representing a user profile, a product listing, or a database row as a dictionary of named fields is one of the most common patterns in real-world Python applications.
- โถ
๐ Routing and Dispatch Tables โ Web frameworks and command-line tools often map string commands or URL paths to handler functions using a dictionary, enabling fast, readable dispatch logic.
Python Dictionary Methods โ Interview Questions
Practice Questions โ Test Your Knowledge
1. What is the output of: d = {'a': 1}; print(d.get('b'))?
Easy2. What is the output of: d = {'x': 1, 'y': 2}; d.update({'y': 5, 'z': 3}); print(d)?
Easy3. How would you safely retrieve a nested dictionary value that might not exist at any level?
Medium4. What is the output of: d = dict.fromkeys(['a', 'b', 'c'], 0); d['a'] = 5; print(d)?
Medium5. Write a dictionary comprehension to invert a dictionary's keys and values.
Medium6. Why does modifying a dictionary while iterating over its keys with a for loop raise a RuntimeError?
Hard7. How would you count the frequency of each word in a sentence using a dictionary?
Hard8. What is the difference between {**dict_a, **dict_b} and dict_a | dict_b?
HardConclusion โ Mastering Python Dictionary Methods
Python dictionaries are the most versatile of all the built-in collection types โ they combine fast, key-based lookup with guaranteed insertion order and the flexibility to store any type of value imaginable. From configuration files to JSON API responses to word-frequency counters, dictionaries appear in nearly every non-trivial Python program.
The single most important habit to build: reach for get() and setdefault() whenever a key's existence isn't guaranteed, rather than square-bracket access โ this one shift eliminates the majority of KeyError crashes new Python developers encounter. Combine that with items() for clean iteration, and you have everything needed to work confidently with dictionaries in production code.
With dictionaries covered, you've now completed all four of Python's core built-in collection types โ lists, tuples, sets, and dictionaries. The next step in your journey is combining them: nested dictionaries of lists, sets of tuples, and the many patterns that emerge once you understand exactly when to reach for each one. Practice each method in the live editor above until the behavior feels automatic. ๐