Lessons
Courses

Dictionary in Python [ English ]

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

  • Stores data in key : value format
  • Mutable (can be modified)
  • Unordered (no fixed index position)
  • Keys must be unique
  • Keys must be immutable (int, string, tuple)

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 # addstudent["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

MethodDescription
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

  • Keys must be unique
  • Values can be duplicated
  • Keys must be immutable
  • Dictionaries are dynamic and flexible

12. Difference Between List and Dictionary

FeatureListDictionary
AccessIndexKey
StructureOrderedKey-value
Syntax[ ]{ }

13. Practical Example

student = { "name": "Rahul", "marks": 80} student["marks"] += 10 print(student)

14. Summary

  • Dictionary stores data as key-value pairs

  • Created using {}

  • Supports:

    • adding
    • updating
    • deleting
  • Keys are unique and immutable

  • Used for structured and fast data access