Notes
Categories

Dictionary in Python [ English ]

< Prev Next >

1. Introduction

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.

2. Characteristics of Dictionary

3. Creating a Dictionary

Syntax

dict_name = {key1: value1, key2: value2}

Example

student = {
    "name": "Rahul",
    "age": 20,
    "marks": 85
}

Empty Dictionary

d = {}

4. Accessing Values

Using Key

student = {"name": "Rahul", "age": 20}

print(student["name"])

Output

Rahul

Using get() Method

print(student.get("age"))

5. Adding and Updating Elements

student = {"name": "Rahul"}

student["age"] = 20      # add
student["name"] = "Amit" # update

print(student)

6. Removing Elements

Using pop()

student.pop("age")

Using del

del student["name"]

Using clear()

student.clear()

7. Dictionary Methods

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

8. Looping Through Dictionary

student = {"name": "Rahul", "age": 20}

for key in student:
    print(key, student[key])

9. Nested Dictionary

students = {
    "s1": {"name": "Rahul", "age": 20},
    "s2": {"name": "Amit", "age": 22}
}

print(students["s1"]["name"])

Output

Rahul

10. Membership Operators

print("name" in student)
print("marks" not in student)

11. Important Points

12. Difference Between List and Dictionary

Feature List Dictionary
Access Index Key
Structure Ordered Key-value
Syntax [ ] { }

13. Practical Example

student = {
    "name": "Rahul",
    "marks": 80
}

student["marks"] += 10

print(student)

14. Summary

< Prev Next >