Creating, Accessing, and Updating Dictionaries in Python
Course: Python Training
Topic: Creating, Accessing, and Updating Dictionaries
Course Link: Python Training Course at JustAcademy
Demo Link: Register for a Free Course Demo
Website: JustAcademy Official Website
1. Introduction to Python Dictionaries
A dictionary is a built-in Python data structure used to store information in key-value pairs. Each key identifies a value, making dictionaries useful when data needs to be accessed using meaningful names instead of numeric positions.
For example, a student's name, age, course, and marks can be stored together in a dictionary. Instead of remembering the position of each value in a list, you can retrieve a value using its corresponding key.
student = {
"name": "Aarav",
"age": 21,
"course": "Python",
"marks": 88
}
print(student)
Output:
{'name': 'Aarav', 'age': 21, 'course': 'Python', 'marks': 88}
2. Learning Objectives
- Understand the purpose and structure of dictionaries.
- Create dictionaries using different approaches.
- Access dictionary values using keys.
- Use the
get() method to retrieve values safely.
- Add new key-value pairs to a dictionary.
- Update existing values and modify multiple entries.
- Remove dictionary entries using common methods.
- Check whether keys exist in a dictionary.
- Apply dictionaries to practical Python programs.
3. What Is a Dictionary?
A dictionary stores related data as pairs. Each pair contains a key and its associated value, separated by a colon. Multiple pairs are separated by commas and enclosed in curly braces.
dictionary_name = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Example:
employee = {
"employee_id": 101,
"name": "Priya",
"department": "IT",
"salary": 45000
}
print(employee["name"])
print(employee["department"])
Output:
Priya
IT
Important Characteristics of Dictionaries
| Characteristic |
Description |
| Key-value structure |
Each entry associates a key with a value. |
| Mutable |
You can add, update, and remove entries after creation. |
| Unique keys |
Each key can appear only once in a dictionary; assigning a duplicate key replaces its previous value. |
| Key requirements |
Keys must be hashable, such as strings, integers, or tuples containing only hashable values. |
| Flexible values |
Values can be strings, numbers, lists, tuples, other dictionaries, or other Python objects. |
| Insertion order |
Modern Python dictionaries preserve the order in which keys are inserted. |
| No numeric indexing |
Dictionary values are normally retrieved using keys rather than list-style numeric positions. |
4. Creating Dictionaries in Python
Python provides several ways to create dictionaries. The most common approach is to use curly braces with key-value pairs.
4.1 Creating a Dictionary Using Curly Braces
person = {
"name": "Rahul",
"age": 25,
"city": "Mumbai"
}
print(person)
Output:
{'name': 'Rahul', 'age': 25, 'city': 'Mumbai'}
This method is suitable when you already know the keys and values you want to store.
4.2 Creating an Empty Dictionary
An empty dictionary is useful when you intend to add data later.
student = {}
print(student)
student["name"] = "Neha"
student["age"] = 20
print(student)
Output:
{}
{'name': 'Neha', 'age': 20}
You can also create an empty dictionary with the dict() constructor.
student = dict()
print(student)
Output:
{}
4.3 Creating a Dictionary with the dict() Constructor
The dict() constructor can create dictionaries from keyword arguments or suitable collections of key-value pairs.
student = dict(name="Ananya", age=22, course="Python")
print(student)
Output:
{'name': 'Ananya', 'age': 22, 'course': 'Python'}
When using keyword arguments, the keys must be valid Python identifiers. Use curly braces when keys contain spaces or special characters.
product = {
"product name": "Keyboard",
"unit-price": 1200
}
print(product["product name"])
Output:
Keyboard
4.4 Creating a Dictionary from Key-Value Pairs
You can build a dictionary from an iterable containing pairs. Each pair supplies one key and one value.
pairs = [
("name", "Karan"),
("age", 24),
("city", "Pune")
]
person = dict(pairs)
print(person)
Output:
{'name': 'Karan', 'age': 24, 'city': 'Pune'}
4.5 Creating a Dictionary with dict.fromkeys()
The fromkeys() method creates a dictionary using the specified keys and a shared initial value.
subjects = ["Python", "SQL", "Excel"]
marks = dict.fromkeys(subjects, 0)
print(marks)
Output:
{'Python': 0, 'SQL': 0, 'Excel': 0}
Important: If the shared value is a mutable object such as a list, all keys refer to that same object. Use a dictionary comprehension when every key needs its own independent list.
subjects = ["Python", "SQL", "Excel"]
marks = {subject: [] for subject in subjects}
marks["Python"].append(90)
print(marks)
Output:
{'Python': [90], 'SQL': [], 'Excel': []}
5. Understanding Dictionary Keys and Values
Dictionary keys are used to identify and retrieve associated values. Values hold the actual information.
book = {
"title": "Learning Python",
"author": "Mark",
"price": 550
}
"title", "author", and "price" are keys.
"Learning Python", "Mark", and 550 are values.
5.1 Keys Must Be Hashable
Strings, integers, and many tuples can be used as dictionary keys. Lists and dictionaries cannot be used as keys because they are mutable and unhashable.
data = {
"name": "Riya",
101: "Employee ID",
(1, 2): "Coordinate"
}
print(data["name"])
print(data[101])
print(data[(1, 2)])
Output:
Riya
Employee ID
Coordinate
Using a list as a key raises a TypeError.
# Invalid example:
# data = {[1, 2]: "value"}
5.2 Duplicate Keys
If a dictionary definition contains the same key more than once, the last assigned value is retained.
scores = {
"Python": 70,
"SQL": 80,
"Python": 95
}
print(scores)
Output:
{'Python': 95, 'SQL': 80}
Use unique keys when each entry needs to represent a different item.
6. Accessing Dictionary Values
After creating a dictionary, you can retrieve its values using square brackets or the get() method.
6.1 Accessing Values Using Square Brackets
Place the required key inside square brackets to retrieve its value.
student = {
"name": "Amit",
"age": 23,
"course": "Data Analytics"
}
print(student["name"])
print(student["age"])
print(student["course"])
Output:
Amit
23
Data Analytics
Important: If the key does not exist, square-bracket access raises a KeyError.
student = {"name": "Amit"}
# This raises KeyError:
# print(student["marks"])
6.2 Accessing Values Using get()
The get() method retrieves a value without raising a KeyError when the key is missing. By default, it returns None for an absent key, or you can specify a default value.
student = {
"name": "Amit",
"age": 23
}
print(student.get("name"))
print(student.get("marks"))
print(student.get("marks", 0))
Output:
Amit
None
0
6.3 Difference Between Square Brackets and get()
| Feature |
Square Brackets |
get() Method |
| Syntax |
data["name"] |
data.get("name") |
| Existing key |
Returns its value. |
Returns its value. |
| Missing key |
Raises KeyError. |
Returns None by default. |
| Custom default |
Not directly supported. |
Supported with get(key, default). |
| Common use |
When the key is expected to exist. |
When a key may be absent. |
6.4 Checking Whether a Key Exists
Use the in operator to determine whether a key exists in a dictionary.
employee = {
"name": "Sneha",
"department": "HR"
}
print("name" in employee)
print("salary" in employee)
print("HR" in employee.values())
Output:
True
False
True
By default, in checks dictionary keys. Use dictionary.values() when you need to check values instead.
7. Adding New Entries to a Dictionary
Since dictionaries are mutable, you can add new key-value pairs after creating them. Assign a value to a key that does not yet exist.
student = {
"name": "Meera",
"age": 21
}
student["course"] = "Python"
student["city"] = "Mumbai"
print(student)
Output:
{'name': 'Meera', 'age': 21, 'course': 'Python', 'city': 'Mumbai'}
When a new key is assigned, Python adds a new entry. If the key already exists, its value is updated instead.
7.1 Adding Data with setdefault()
The setdefault() method returns the existing value for a key. If the key is absent, it inserts the key with the supplied default value and returns that value.
student = {"name": "Meera"}
age = student.setdefault("age", 21)
course = student.setdefault("course", "Python")
print(age)
print(course)
print(student)
Output:
21
Python
{'name': 'Meera', 'age': 21, 'course': 'Python'}
If a key already exists, setdefault() does not overwrite its current value.
student = {"age": 22}
student.setdefault("age", 18)
print(student)
Output:
{'age': 22}
8. Updating Existing Dictionary Values
Updating means changing the value associated with a key that already exists. Assign a new value using the key.
employee = {
"name": "Rahul",
"department": "Sales",
"salary": 30000
}
employee["department"] = "Marketing"
employee["salary"] = 35000
print(employee)
Output:
{'name': 'Rahul', 'department': 'Marketing', 'salary': 35000}
8.1 Updating Multiple Entries with update()
The update() method adds new entries and updates existing ones using data from another dictionary or a suitable iterable of key-value pairs.
employee = {
"name": "Rahul",
"department": "Sales",
"salary": 30000
}
employee.update({
"department": "Marketing",
"salary": 35000,
"city": "Pune"
})
print(employee)
Output:
{'name': 'Rahul', 'department': 'Marketing', 'salary': 35000, 'city': 'Pune'}
In this example, the department and salary values are updated, and a new city entry is added.
8.2 Updating with Keyword Arguments
You can pass keyword arguments to update() when the keys are valid Python identifiers.
settings = {
"theme": "light",
"language": "English"
}
settings.update(theme="dark", language="Hindi")
print(settings)
Output:
{'theme': 'dark', 'language': 'Hindi'}
8.3 Updating Nested Dictionaries
A dictionary can contain another dictionary as a value. To update a nested value, access the inner dictionary through its key.
student = {
"name": "Anaya",
"address": {
"city": "Mumbai",
"state": "Maharashtra"
}
}
student["address"]["city"] = "Pune"
print(student["address"])
Output:
{'city': 'Pune', 'state': 'Maharashtra'}
You can also update several fields within the nested dictionary.
student["address"].update({
"city": "Nashik",
"state": "Maharashtra"
})
print(student["address"])
Output:
{'city': 'Nashik', 'state': 'Maharashtra'}
9. Removing Dictionary Entries
Although the main focus is creating, accessing, and updating dictionaries, removing entries is an important part of managing dictionary data.
9.1 Using pop()
The pop() method removes the specified key and returns its value. You can supply a default value to avoid an error if the key is missing.
student = {
"name": "Rohan",
"age": 22,
"course": "Python"
}
removed_course = student.pop("course")
print(removed_course)
print(student)
Output:
Python
{'name': 'Rohan', 'age': 22}
Using a default value prevents a KeyError for a missing key.
student = {"name": "Rohan"}
print(student.pop("marks", "Not available"))
Output:
Not available
9.2 Using del
The del statement removes a specific key-value pair.
student = {
"name": "Rohan",
"age": 22
}
del student["age"]
print(student)
Output:
{'name': 'Rohan'}
9.3 Using popitem()
The popitem() method removes and returns the most recently inserted key-value pair in modern Python dictionaries.
student = {
"name": "Rohan",
"age": 22,
"course": "Python"
}
item = student.popitem()
print(item)
print(student)
Output:
('course', 'Python')
{'name': 'Rohan', 'age': 22}
9.4 Using clear()
The clear() method removes every entry while keeping the dictionary object available.
student = {
"name": "Rohan",
"age": 22
}
student.clear()
print(student)
Output:
{}
10. Useful Dictionary Methods
| Method |
Purpose |
Example |
get() |
Retrieves a value safely. |
data.get("name", "Unknown") |
keys() |
Returns a dynamic view of dictionary keys. |
data.keys() |
values() |
Returns a dynamic view of dictionary values. |
data.values() |
items() |
Returns a dynamic view of key-value pairs. |
data.items() |
update() |
Adds entries and updates existing values. |
data.update({"age": 25}) |
setdefault() |
Returns an existing value or inserts a default. |
data.setdefault("city", "Pune") |
pop() |
Removes a specified key and returns its value. |
data.pop("age", None) |
popitem() |
Removes and returns the last inserted pair. |
data.popitem() |
clear() |
Removes all entries. |
data.clear() |
copy() |
Creates a shallow copy. |
new_data = data.copy() |
11. Iterating Through Dictionaries
Iteration allows you to process dictionary keys, values, or complete key-value pairs. This is useful for displaying records, performing calculations, and validating information.
11.1 Iterating Through Keys
student = {
"name": "Isha",
"age": 21,
"course": "Python"
}
for key in student:
print(key)
Output:
name
age
course
11.2 Iterating Through Values
student = {
"name": "Isha",
"age": 21,
"course": "Python"
}
for value in student.values():
print(value)
Output:
Isha
21
Python
11.3 Iterating Through Key-Value Pairs
student = {
"name": "Isha",
"age": 21,
"course": "Python"
}
for key, value in student.items():
print(key, ":", value)
Output:
name : Isha
age : 21
course : Python
12. Practical Example: Student Record Management
Consider a student record that stores a student's name, age, course, and marks. The following example demonstrates dictionary creation, accessing, updating, adding, and removing entries in one program.
# Create a student dictionary
student = {
"name": "Aarav",
"age": 20,
"course": "Python",
"marks": 75
}
# Access existing values
print("Student:", student["name"])
print("Current marks:", student.get("marks"))
# Update marks
student["marks"] = 92
# Add a new entry
student["city"] = "Mumbai"
# Update multiple entries
student.update({
"age": 21,
"course": "Advanced Python"
})
# Display the final record
print("Updated student record:")
for key, value in student.items():
print(key, ":", value)
Output:
Student: Aarav
Current marks: 75
Updated student record:
name : Aarav
age : 21
course : Advanced Python
marks : 92
city : Mumbai
Explanation:
- The dictionary is created with four initial entries.
- Square brackets and
get() retrieve existing information.
- The marks value is changed from 75 to 92.
- A city entry is added.
- The
update() method changes the age and course.
- The
items() method allows the final record to be displayed as key-value pairs.
13. Practical Example: Product Inventory
Dictionaries are useful in inventory applications because each product can be identified by a product code and associated with a quantity or price.
inventory = {
"P101": {
"name": "Keyboard",
"price": 1200,
"quantity": 10
},
"P102": {
"name": "Mouse",
"price": 600,
"quantity": 15
}
}
# Access a product
print(inventory["P101"]["name"])
# Update stock quantity
inventory["P101"]["quantity"] = 8
# Add a new product
inventory["P103"] = {
"name": "Monitor",
"price": 8500,
"quantity": 5
}
# Display inventory
for product_id, details in inventory.items():
print(product_id, details)
Output:
Keyboard
P101 {'name': 'Keyboard', 'price': 1200, 'quantity': 8}
P102 {'name': 'Mouse', 'price': 600, 'quantity': 15}
P103 {'name': 'Monitor', 'price': 8500, 'quantity': 5}
14. Practical Example: Counting Word Frequencies
A dictionary can count how many times each word appears in a sentence. The word is the key, and its frequency is the value.
sentence = "python is easy and python is useful"
word_counts = {}
for word in sentence.split():
word_counts[word] = word_counts.get(word, 0) + 1
print(word_counts)
Output:
{'python': 2, 'is': 2, 'easy': 1, 'and': 1, 'useful': 1}
How it works:
split() divides the sentence into words.
- The loop processes each word.
get(word, 0) returns the current count or zero if the word has not appeared.
- Adding one increases the word's frequency.
- The resulting dictionary contains each word and its count.
15. Dictionary Copying and Assignment
It is important to understand the difference between assigning a dictionary to another variable and creating a copy.
15.1 Assignment Creates Another Reference
original = {"name": "Asha", "age": 22}
reference = original
reference["age"] = 23
print(original)
Output:
{'name': 'Asha', 'age': 23}
Both variables refer to the same dictionary. Therefore, changing the dictionary through either variable affects the same object.
15.2 Creating a Shallow Copy
original = {"name": "Asha", "age": 22}
copied = original.copy()
copied["age"] = 23
print(original)
print(copied)
Output:
{'name': 'Asha', 'age': 22}
{'name': 'Asha', 'age': 23}
The copy() method creates a new outer dictionary. However, nested mutable objects are still shared between the original and the shallow copy. Use copy.deepcopy() from the copy module when an independent deep copy is required.
16. Common Mistakes and How to Avoid Them
| Mistake |
Why It Happens |
Correct Approach |
| Accessing a missing key with square brackets |
Raises KeyError. |
Check with in or use get(). |
| Using a list as a key |
Lists are unhashable. |
Use a string, integer, or suitable tuple key. |
| Confusing keys with values |
The in operator checks keys by default. |
Use values() to search values. |
| Expecting update() to return a new dictionary |
update() modifies the dictionary in place and returns None. |
Call update() separately, then use the modified dictionary. |
| Assuming assignment creates a copy |
Both variables reference the same object. |
Use copy() or deepcopy() as needed. |
| Overwriting data accidentally |
Assigning an existing key replaces its value. |
Check the key or use setdefault() if you want to preserve existing values. |
| Using a shared mutable default carelessly |
dict.fromkeys(keys, []) shares one list across all keys. |
Use a dictionary comprehension to create separate lists. |
| Modifying dictionary size during iteration |
Adding or removing keys during a direct iteration can raise an error or lead to unexpected behavior. |
Iterate over a snapshot such as list(data.items()) when changing keys. |
17. Best Practices for Working with Dictionaries
- Choose clear, descriptive keys such as
student_name instead of vague keys such as x.
- Use square brackets when a key is expected to exist and use
get() when a missing key is possible.
- Check for key existence before performing operations that require a particular entry.
- Use
update() when changing several fields at once.
- Keep dictionary structures consistent when storing multiple records of the same type.
- Use nested dictionaries for logically grouped information, such as addresses or product details.
- Avoid duplicate keys in dictionary literals because later values overwrite earlier ones.
- Use
items() when both keys and values are needed in a loop.
- Be aware of shallow-copy behavior when dictionaries contain lists or other mutable objects.
- Use meaningful defaults so that missing information is handled correctly.
18. Exercises for Practice
Exercise 1: Create a Personal Profile
Create a dictionary named profile containing your name, age, city, and profession. Print each value separately.
Exercise 2: Add and Update Entries
Create a dictionary containing three subjects and their marks. Add a fourth subject, then update the marks for one existing subject.
Exercise 3: Safe Access
Create a dictionary containing a product name and price. Use get() to retrieve the price and return "Not available" if the stock quantity key does not exist.
Exercise 4: Remove an Entry
Create an employee dictionary and remove the department entry using pop(). Print the removed value and the remaining dictionary.
Exercise 5: Inventory Management
Create a nested dictionary containing three products. Each product should have a name, price, and quantity. Update one product's quantity and add a new product.
Exercise 6: Count Character Frequencies
Write a program that counts the number of times each character appears in a string. Store the characters and their counts in a dictionary.
Exercise 7: Find Missing Information
Create a student dictionary with name and course details. Check whether the marks key exists and print an appropriate message if it is missing.
19. Interview Questions and Answers
Q1. What is a dictionary in Python?
A dictionary is a mutable built-in data structure that stores information as key-value pairs. Values are retrieved using their corresponding keys.
Q2. How do you create an empty dictionary?
You can use either data = {} or data = dict().
Q3. How do you access a dictionary value?
Use square brackets, such as data["name"], or use data.get("name") for safer access when the key might not exist.
Q4. What happens when you access a missing key with square brackets?
Python raises a KeyError.
Q5. What is the difference between get() and setdefault()?
get() retrieves a value or returns a default without inserting a missing key. setdefault() inserts the key with a default value if the key is missing.
Q6. How can you add a new key-value pair?
Assign a value to a new key, for example, data["city"] = "Mumbai".
Q7. How do you update multiple dictionary entries?
Use the update() method, for example, data.update({"age": 25, "city": "Pune"}).
Q8. Can dictionary keys be duplicated?
A dictionary cannot retain duplicate keys. If the same key is assigned multiple times, the most recent value is retained.
Q9. Can a list be used as a dictionary key?
No. Lists are mutable and unhashable, so they cannot be used as dictionary keys.
Q10. What is the difference between keys(), values(), and items()?
keys() provides a view of keys, values() provides a view of values, and items() provides a view of key-value pairs.
Q11. How do you delete a dictionary entry?
You can use del data["key"] or data.pop("key"). The pop() method also returns the removed value.
Q12. What is the difference between clear() and pop()?
clear() removes every entry from the dictionary, whereas pop() removes a specific key and returns its value.
Q13. Does update() create a new dictionary?
No. It modifies the existing dictionary in place and returns None.
Q14. Are Python dictionaries ordered?
Yes. Python dictionaries preserve insertion order in modern Python versions.
Q15. What is a nested dictionary?
A nested dictionary is a dictionary whose value contains another dictionary. It is useful for representing grouped information such as employee details and addresses.
20. Quick Revision Checklist
- Understand that dictionaries store key-value pairs.
- Create dictionaries using curly braces or
dict().
- Retrieve values with square brackets or
get().
- Use the
in operator to check for keys.
- Add entries through key assignment.
- Change existing values through assignment or
update().
- Use
setdefault() to insert a default only when a key is missing.
- Remove entries using
pop(), del, or popitem().
- Use
keys(), values(), and items() for iteration.
- Understand nested dictionaries and shallow copying.
- Handle missing keys and mutable values carefully.
21. Conclusion
Python dictionaries provide a flexible and efficient way to organize data using meaningful keys. Creating dictionaries lets you group related information, accessing values helps retrieve the required data, and updating dictionaries allows records to change as a program runs. Methods such as get(), update(), setdefault(), and pop() make dictionary operations easier and safer.
Practicing these operations with student records, employee details, product inventories, and word-frequency programs will help you build a strong foundation for more advanced Python topics, including nested data structures, JSON handling, APIs, and data processing.
Explore the course: Python Training at JustAcademy | Register for a Course Demo | Visit JustAcademy