๐Ÿ—‚๏ธ Python Dictionaries

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.

๐Ÿ Pythonbasic_dict.py
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.

๐Ÿ Pythoncreating_dicts.py
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} Priya

Accessing 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.

๐Ÿ Pythonkeyerror_example.py
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:

๐Ÿ”
get()

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.

๐Ÿ”‘
keys()

Returns a view object displaying all the keys in the dictionary, in insertion order, which stays live-synced with the dictionary.

๐Ÿ“ฆ
values()

Returns a view object displaying all the values in the dictionary, in the same order as their corresponding keys.

๐Ÿงพ
items()

Returns a view object of (key, value) tuple pairs โ€” the most common way to iterate over both keys and values together.

๐Ÿ”„
update()

Merges another dictionary (or iterable of key-value pairs) into the current one, overwriting values for any matching keys.

๐Ÿ“ค
pop()

Removes a specified key and returns its value. Accepts an optional default to avoid a KeyError if the key is missing.

๐ŸŽฒ
popitem()

Removes and returns the last inserted key-value pair as a tuple. Raises a KeyError if the dictionary is empty.

๐Ÿงฉ
setdefault()

Returns the value for a key if it exists; otherwise inserts the key with a default value and returns that default.

๐Ÿญ
fromkeys()

A class method that builds a new dictionary from a sequence of keys, all mapped to the same specified value.

๐Ÿงน
clear()

Removes all key-value pairs from the dictionary, leaving it empty.

๐ŸงŠ
copy()

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.

๐Ÿ Pythonget_example.py
student = {"name": "Priya", "age": 21}
print(student.get("name"))
print(student.get("grade"))
print(student.get("grade", "Not Assigned"))

Output

Priya None Not Assigned

As 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.

๐Ÿ Pythonkeys_values_items_example.py
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:

๐Ÿ Pythonitems_loop_example.py
for key, value in student.items():
    print(f"{key}: {value}")

Output

name: Priya age: 21 course: Python

Because 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.

๐Ÿ Pythonupdate_example.py
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.

๐Ÿ Pythonpop_example.py
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.

๐Ÿ Pythonpopitem_example.py
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

๐Ÿ Pythonclear_example.py
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.

๐Ÿ Pythonsetdefault_example.py
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.

๐Ÿ Pythonsetdefault_grouping.py
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).

๐Ÿ Pythonfromkeys_example.py
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.

๐Ÿ Pythonfromkeys_mutable_trap.py
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.

๐Ÿ Pythoncopy_example.py
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.

๐Ÿ”‘ Access: my_dict[key]or my_dict.get(key)
hash key
โšก Compute hash(key)Convert key to hash value
index table
๐Ÿ“ Locate BucketJump to hash table slot
verify match
โ“ Key Found?Compare stored key
not found
โŒ [] โ†’ KeyErrorget() โ†’ default/None
๐Ÿ–จ๏ธ Return ValueValue returned instantly

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.

MethodPurposeReturnsModifies Original?
get(key, default)Safely retrieve valueValue or defaultNo
keys()View of all keysdict_keys viewNo
values()View of all valuesdict_values viewNo
items()View of key-value pairsdict_items viewNo
update(other)Merge another dict/iterable inNoneYes
pop(key, default)Remove key, return its valueRemoved valueYes
popitem()Remove last inserted pair(key, value) tupleYes
setdefault(key, default)Get or insert with defaultExisting or new valueYes (if key missing)
fromkeys(seq, value)Build dict from key sequenceNew dictNo (class method)
clear()Remove all pairsNoneYes
copy()Create shallow copyNew dictNo

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}.

๐Ÿ Pythondict_comprehension_example.py
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:

๐Ÿ Pythondict_comprehension_filter.py
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.

FeatureDictionaryListTupleSet
Syntax{'a': 1}[1, 2, 3](1, 2, 3){1, 2, 3}
Mutable?โœ… Yesโœ… YesโŒ Noโœ… Yes
Ordered?โœ… Yes (3.7+)โœ… Yesโœ… YesโŒ No
Access methodBy keyBy indexBy indexNo direct access
Duplicates allowed?Keys: No, Values: Yesโœ… Yesโœ… YesโŒ No
Lookup speedO(1) average (by key)O(n) by valueO(n) by valueO(1) average
Common use caseKey-value mapping, recordsOrdered growing dataFixed recordsUniqueness, fast lookup

Advantages and Disadvantages of Dictionaries

โœ… Advantages
Extremely Fast Key LookupRetrieving a value by its key is O(1) on average, regardless of how many entries the dictionary contains โ€” far faster than searching a list for a matching value.
Self-Documenting StructureAccessing student['name'] is immediately more readable than student[0], since the key describes exactly what the value represents.
Guaranteed Insertion OrderSince Python 3.7, dictionaries reliably preserve the order keys were first added, making iteration predictable and consistent.
Flexible Value TypesDictionary values can be any type at all โ€” including lists, other dictionaries, or custom objects โ€” enabling deeply nested, structured data.
Rich Built-in Methodsget(), setdefault(), update(), and the view objects (keys/values/items) cover nearly every common data manipulation need without external libraries.
โŒ Disadvantages
Keys Must Be HashableYou cannot use a list or another dictionary as a key โ€” only immutable types like strings, numbers, or tuples of hashable elements are allowed.
No Positional IndexingUnlike lists, you cannot access the 'third item' of a dictionary directly by a numeric index โ€” access is purely key-based.
Higher Memory OverheadThe underlying hash table structure, plus the separate order-tracking array, uses more memory per entry than an equivalent list of tuples.
Key Collisions Overwrite SilentlyAssigning to an existing key silently replaces its value with no warning, which can hide bugs if a key is unintentionally reused.

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'))?

Easy

2. What is the output of: d = {'x': 1, 'y': 2}; d.update({'y': 5, 'z': 3}); print(d)?

Easy

3. How would you safely retrieve a nested dictionary value that might not exist at any level?

Medium

4. What is the output of: d = dict.fromkeys(['a', 'b', 'c'], 0); d['a'] = 5; print(d)?

Medium

5. Write a dictionary comprehension to invert a dictionary's keys and values.

Medium

6. Why does modifying a dictionary while iterating over its keys with a for loop raise a RuntimeError?

Hard

7. How would you count the frequency of each word in a sentence using a dictionary?

Hard

8. What is the difference between {**dict_a, **dict_b} and dict_a | dict_b?

Hard

Conclusion โ€” 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.

Your GoalRecommended Method
Safely retrieve a value that might be missingโœ… get()
Loop over keys and values togetherโœ… items()
Merge another dict in, overwriting duplicatesโœ… update()
Remove a key and use its valueโœ… pop()
Remove the most recently added pairโœ… popitem()
Get a value or insert a default if missingโœ… setdefault()
Build a dict from a list of keysโœ… fromkeys()
Empty the whole dictionaryโœ… clear()
Create an independent duplicateโœ… copy()

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. ๐Ÿ

Frequently Asked Questions (FAQ)