A Python dictionary is a collection used to store data in key-value pairs. Each key is used to identify its corresponding value.
Dictionaries are written using curly braces {}.
student = {
"name": "Rahul",
"age": 21,
"city": "Delhi"
}
print(student)Output:
{'name': 'Rahul', 'age': 21, 'city': 'Delhi'}A dictionary is useful when you want to store related information and access it using meaningful keys instead of index numbers.
What is a Dictionary?
A dictionary stores data in the form:
key: value
For example:
student = {
"name": "Rahul",
"age": 21,
"course": "Python"
}Here, "name", "age", and "course" are keys, while "Rahul", 21, and "Python" are their values.
Keys must be unique within a dictionary. Values can be of different data types.
data = {
"name": "Amit",
"age": 25,
"marks": 85.5,
"passed": True
}Creating Dictionaries
A dictionary can be created by placing key-value pairs inside curly braces.
person = {
"name": "Amit",
"age": 25,
"country": "India"
}You can also create an empty dictionary:
mydict = {}Another way is to use the dict() constructor:
student = dict(name="Rahul", age=21, city="Delhi")
print(student)Output:
{'name': 'Rahul', 'age': 21, 'city': 'Delhi'}Accessing Items
Dictionary values can be accessed using their keys.
student = {
"name": "Rahul",
"age": 21,
"city": "Delhi"
}
print(student["name"])
print(student["age"])Output:
Rahul
21You can also use the get() method to access a value:
print(student.get("city"))Output:
DelhiThe get() method is useful when a key may not exist because it returns None instead of raising a KeyError.
print(student.get("email"))Output:
NoneAdding and Updating Items
You can add a new item by assigning a value to a new key.
student = {
"name": "Rahul",
"age": 21
}
student["city"] = "Delhi"
print(student)Output:
{'name': 'Rahul', 'age': 21, 'city': 'Delhi'}If the key already exists, assigning a new value updates the existing item.
student["age"] = 22
print(student)Output:
{'name': 'Rahul', 'age': 22, 'city': 'Delhi'}The update() method can be used to add or update multiple items:
student.update({
"course": "Python",
"age": 23
})
print(student)Removing Items
Python provides several ways to remove items from a dictionary.
The pop() method removes an item using its key:
student = {
"name": "Rahul",
"age": 21,
"city": "Delhi"
}
student.pop("age")
print(student)Output:
{'name': 'Rahul', 'city': 'Delhi'}The popitem() method removes the last inserted key-value pair:
student.popitem()
print(student)You can use the del statement to remove a specific item:
del student["city"]To remove all items from a dictionary, use clear():
student.clear()
print(student)Output:
{}Dictionary Methods
Python dictionaries provide several useful methods for working with keys and values.
keys()
The keys() method returns all keys:
student = {
"name": "Rahul",
"age": 21,
"city": "Delhi"
}
print(student.keys())values()
The values() method returns all values:
print(student.values())items()
The items() method returns the dictionary's key-value pairs:
print(student.items())get()
get() returns the value associated with a key:
print(student.get("name"))update()
update() adds new items or changes existing ones:
student.update({"age": 22})copy()
The copy() method creates a copy of a dictionary:
new_student = student.copy()Iterating Through a Dictionary
You can use a for loop to iterate through a dictionary.
By default, the loop goes through the keys:
student = {
"name": "Rahul",
"age": 21,
"city": "Delhi"
}
for key in student:
print(key)To get the values, use values():
for value in student.values():
print(value)You can get both keys and values using items():
for key, value in student.items():
print(key, value)Output:
name Rahul
age 21
city DelhiNested Dictionaries
A nested dictionary is a dictionary that contains another dictionary as a value.
students = {
"student1": {
"name": "Rahul",
"age": 21
},
"student2": {
"name": "Amit",
"age": 22
}
}
print(students)You can access values from a nested dictionary using multiple keys:
print(students["student1"]["name"])Output:
RahulNested dictionaries are useful for storing structured data, such as information about multiple students, employees, products, or customers.
Dictionary Comprehension
Dictionary comprehension provides a short way to create dictionaries using an expression and a loop.
For example, instead of writing:
numbers = {}
for x in range(1, 6):
numbers[x] = x * x
print(numbers)You can use dictionary comprehension:
numbers = {x: x * x for x in range(1, 6)}
print(numbers)Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}The basic syntax is:
{key: value for item in iterable}You can also add a condition:
numbers = {x: x * x for x in range(1, 11) if x % 2 == 0}
print(numbers)Output:
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}Dictionary comprehension is useful when a dictionary needs to be created from an iterable with a simple rule or condition.