A dictionary in Python is a mutable data structure that stores information as key-value pairs. Each key identifies a value, allowing programs to retrieve data using a meaningful identifier instead of a numeric index.
Dictionaries are one of the most important data structures in Python. They are commonly used for configuration data, user profiles, API responses, caches, lookup tables, frequency counting, grouping data, and many algorithmic problems.
Python dictionaries preserve insertion order, but they are primarily designed around key-based access rather than positional access.
Creating a Dictionary
A dictionary is usually created using curly braces with keys and values separated by a colon.
user = {
"id": 101,
"name": "Alice",
"role": "Developer"
}
print(user)
An empty dictionary can be created using {} or
dict().
user_one = {}
user_two = dict()
print(user_one)
print(user_two)
Dictionary Keys and Values
Every dictionary entry contains a key and its associated value. Keys must be unique within a dictionary. Values can be duplicated and can have different data types.
profile = {
"name": "Alice",
"age": 28,
"active": True,
"skills": ["Python", "SQL"]
}
print(profile["name"])
print(profile["skills"])
Dictionary keys must be hashable. Common key types include strings, integers, and tuples containing hashable values.
Accessing Dictionary Values
A value can be accessed using its key inside square brackets.
user = {
"name": "Alice",
"role": "Developer"
}
print(user["name"])
print(user["role"])
Accessing a key that does not exist with square brackets raises a
KeyError.
Using get()
The get() method provides a safer way to retrieve
a value when the key may not exist.
user = {
"name": "Alice",
"role": "Developer"
}
print(user.get("name"))
print(user.get("email"))
print(user.get("phone", "Not provided"))
If the key is missing and no default value is supplied, get()
returns None.
Adding and Updating Dictionary Entries
Assigning a value to a new key adds an entry. Assigning a value to an existing key updates that entry.
user = {
"name": "Alice",
"role": "Developer"
}
user["experience"] = 5
user["role"] = "Senior Developer"
print(user)
This behavior makes dictionaries convenient for gradually building and updating structured data.
Updating Multiple Values with update()
The update() method adds or replaces multiple
key-value pairs at once.
user = {
"name": "Alice",
"role": "Developer"
}
user.update({
"role": "Senior Developer",
"experience": 5,
"location": "Hyderabad"
})
print(user)
Removing Dictionary Entries
pop()
The pop() method removes a specified key and returns
its associated value.
user = {
"name": "Alice",
"role": "Developer",
"experience": 5
}
role = user.pop("role")
print("Removed:", role)
print(user)
A default value can be supplied to avoid an exception when the key does not exist.
popitem()
The popitem() method removes and returns the last
inserted key-value pair.
user = {
"name": "Alice",
"role": "Developer",
"experience": 5
}
item = user.popitem()
print("Removed:", item)
print(user)
del
The del statement can remove a dictionary entry
using its key.
user = {
"name": "Alice",
"role": "Developer"
}
del user["role"]
print(user)
clear()
The clear() method removes all entries from
the dictionary.
user = {
"name": "Alice",
"role": "Developer"
}
user.clear()
print(user)
Checking Whether a Key Exists
The in operator checks whether a key exists in a dictionary.
This operation checks keys, not values.
user = {
"name": "Alice",
"role": "Developer"
}
print("name" in user)
print("email" in user)
To check values instead, use values().
user = {
"name": "Alice",
"role": "Developer"
}
print("Developer" in user.values())
Getting Dictionary Keys, Values, and Items
Python provides keys(),
values(), and
items() methods for working with dictionary contents.
user = {
"name": "Alice",
"role": "Developer",
"experience": 5
}
print(user.keys())
print(user.values())
print(user.items())
Iterating Over a Dictionary
Iterating directly over a dictionary produces its keys.
user = {
"name": "Alice",
"role": "Developer"
}
for key in user:
print(key)
Use items() when both keys and values are needed.
user = {
"name": "Alice",
"role": "Developer",
"experience": 5
}
for key, value in user.items():
print(key, ":", value)
Dictionary Length
The built-in len() function returns the number
of key-value pairs in a dictionary.
user = {
"name": "Alice",
"role": "Developer",
"experience": 5
}
print(len(user))
Dictionary Comprehension
A dictionary comprehension provides a concise way to create dictionaries from iterable data.
numbers = [1, 2, 3, 4, 5]
squares = {
number: number * number
for number in numbers
}
print(squares)
Conditions can also be used in dictionary comprehensions.
numbers = [1, 2, 3, 4, 5, 6]
even_squares = {
number: number * number
for number in numbers
if number % 2 == 0
}
print(even_squares)
Nested Dictionaries
Dictionaries can contain other dictionaries. This is useful for representing hierarchical or structured information.
users = {
"user1": {
"name": "Alice",
"role": "Developer"
},
"user2": {
"name": "Bob",
"role": "Designer"
}
}
print(users["user1"]["name"])
print(users["user2"]["role"])
Dictionaries with Lists
Dictionary values can also be lists. This pattern is useful for representing one-to-many relationships.
developer = {
"name": "Alice",
"skills": [
"Python",
"SQL",
"Git"
]
}
print(developer["skills"])
developer["skills"].append("Docker")
print(developer["skills"])
Dictionary with Tuple Keys
Since tuples can be hashable when their elements are hashable, they can be used as dictionary keys. This is useful for representing coordinates or compound identifiers.
locations = {
(17.3850, 78.4867): "Hyderabad",
(12.9716, 77.5946): "Bengaluru"
}
print(locations[(17.3850, 78.4867)])
Frequency Counting with a Dictionary
Dictionaries are frequently used in algorithms to count occurrences of values. The key represents the value being counted, while the dictionary value stores its frequency.
numbers = [10, 20, 10, 30, 20, 10]
frequency = {}
for number in numbers:
frequency[number] = frequency.get(number, 0) + 1
print(frequency)
Python also provides collections.Counter for
frequency-counting tasks.
Grouping Values with a Dictionary
A dictionary can group multiple values under the same logical key. For example, products can be grouped by category.
products = [
("Laptop", "Electronics"),
("Phone", "Electronics"),
("Desk", "Furniture"),
("Chair", "Furniture")
]
grouped = {}
for product, category in products:
grouped.setdefault(category, []).append(product)
print(grouped)
Dictionary get() for Default Values
The get() method is especially useful when building
lookup logic where a missing key should start with a default value.
scores = {}
scores["Alice"] = scores.get("Alice", 0) + 10
scores["Alice"] = scores.get("Alice", 0) + 15
scores["Bob"] = scores.get("Bob", 0) + 20
print(scores)
setdefault() Method
The setdefault() method returns the value for a key
if it exists. If the key does not exist, it inserts the key with the supplied default value.
groups = {}
groups.setdefault("backend", []).append("Python")
groups.setdefault("backend", []).append("C#")
groups.setdefault("frontend", []).append("JavaScript")
print(groups)
Copying a Dictionary
Assigning one dictionary variable to another does not create an independent dictionary. Both variables refer to the same object.
user = {
"name": "Alice"
}
other = user
other["role"] = "Developer"
print(user)
print(other)
Use copy() to create a shallow copy.
user = {
"name": "Alice",
"role": "Developer"
}
other = user.copy()
other["role"] = "Designer"
print("Original:", user)
print("Copy:", other)
A shallow copy creates a new dictionary, but nested mutable objects can still be shared.
Use copy.deepcopy() when a complete recursive copy is required.
Dictionary Time Complexity
Python dictionaries are implemented using hash-table techniques. Many common key-based operations have O(1) average-case complexity.
| Operation | Average Complexity |
|---|---|
| Access by key | O(1) |
| Insert | O(1) |
| Update | O(1) |
| Delete by key | O(1) |
| Key membership | O(1) |
| Iteration | O(n) |
These are average-case characteristics. Hash-table operations can have different behavior in unusual collision scenarios, while resizing can also make individual operations more expensive.
Dictionary vs List
Lists and dictionaries solve different data-access problems. A list is generally appropriate when data is naturally sequential and accessed by position. A dictionary is more suitable when values need to be retrieved using keys.
| Feature | List | Dictionary |
|---|---|---|
| Access | By index | By key |
| Duplicates | Allowed | Keys are unique |
| Membership | O(n) typical | O(1) average for keys |
| Best suited for | Ordered sequences | Key-value relationships |
Common Dictionary Mistakes in Python
- Trying to access dictionary values using numeric indexes as if the dictionary were a list.
- Assuming dictionary keys can be duplicated.
- Using a mutable object such as a list as a dictionary key.
- Using square-bracket access when a missing key is expected and
get()would be safer. - Confusing
keys(),values(), anditems(). - Modifying a dictionary's size while directly iterating over it.
- Assuming
copy()performs a deep copy of nested objects. - Using a dictionary when an ordered sequence or set better matches the actual requirement.
Practical Example: User Lookup
Dictionaries are useful for quickly finding records by a unique identifier. The following example creates a lookup table using user IDs.
users = {
101: {
"name": "Alice",
"role": "Developer"
},
102: {
"name": "Bob",
"role": "Designer"
},
103: {
"name": "Charlie",
"role": "Tester"
}
}
user_id = 102
user = users.get(user_id)
if user:
print("Name:", user["name"])
print("Role:", user["role"])
else:
print("User not found")
Key Takeaways
- Python dictionaries store data as key-value pairs.
- Dictionary keys must be unique and hashable.
- Values can be any appropriate Python object, including lists and other dictionaries.
- Use square brackets for direct access when the key is known to exist.
- Use get() when a missing key should be handled with a default value.
- update() can add or replace multiple entries.
- pop(), popitem(), del, and clear() provide different removal operations.
- keys(), values(), and items() provide useful views of dictionary contents.
- Dictionaries are commonly used for lookup tables, frequency counting, grouping, and structured application data.
- Key-based insertion, lookup, update, and deletion are typically O(1) on average.