A dictionary in Python is a collection of key-value pairs. It is used to store data in a structured form where each value is associated with a unique key.
dict_name = {key1: value1, key2: value2}
student = {
"name": "Rahul",
"age": 20,
"marks": 85
}
d = {}
student = {"name": "Rahul", "age": 20}
print(student["name"])
Output
Rahul
get() Methodprint(student.get("age"))
student = {"name": "Rahul"}
student["age"] = 20 # add
student["name"] = "Amit" # update
print(student)
pop()student.pop("age")
deldel student["name"]
clear()student.clear()
| Method | Description |
|---|---|
keys() |
Returns all keys |
values() |
Returns all values |
items() |
Returns key-value pairs |
update() |
Updates dictionary |
pop() |
Removes element |
clear() |
Removes all elements |
student = {"name": "Rahul", "age": 20}
for key in student:
print(key, student[key])
students = {
"s1": {"name": "Rahul", "age": 20},
"s2": {"name": "Amit", "age": 22}
}
print(students["s1"]["name"])
Output
Rahul
print("name" in student)
print("marks" not in student)
| Feature | List | Dictionary |
|---|---|---|
| Access | Index | Key |
| Structure | Ordered | Key-value |
| Syntax | [ ] |
{ } |
student = {
"name": "Rahul",
"marks": 80
}
student["marks"] += 10
print(student)
Dictionary stores data as key-value pairs
Created using {}
Supports:
Keys are unique and immutable
Used for structured and fast data access