Some text some message..
Back 9 🟡 Python Dictionaries – A Detailed Explanation 21 Jun, 2025

🔹 What is a Dictionary?

A dictionary in Python is a collection of key-value pairs.

✅ It's like a real-life dictionary – you look up a word (key) to find its definition (value).


🔹 Key Features of a Dictionary

Feature Description
Key-Value Pairs Each item is a pair: key: value
Unordered Python 3.6+: preserves insertion order
Mutable Can change, add, or remove items
Indexed by Keys Access values using keys, not indices
No Duplicates Keys must be unique

🔹 How to Create a Dictionary

# Using curly braces
student = {"name": "Abhi", "age": 25, "grade": "A"}

# Using dict() constructor
employee = dict(id=101, dept="HR", active=True)

🔹 Accessing Items

print(student["name"])         # Output: Abhi
print(student.get("age"))      # Output: 25

🔸 .get() is safer – returns None if key doesn't exist (no error).


🔹 Adding or Modifying Items

student["age"] = 26             # Modify
student["gender"] = "Male"      # Add new key-value pair

🔹 Removing Items

student.pop("grade")            # Remove by key
student.popitem()               # Remove last item
del student["name"]             # Delete by key
student.clear()                 # Remove all items

🔹 Looping Through a Dictionary

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

for key, value in student.items():
    print(key, "=>", value)

🔹 Useful Dictionary Methods

Method Description
keys() Returns all keys
values() Returns all values
items() Returns key-value pairs as tuples
update() Merges another dictionary
get(key) Returns value of the key or None

🔹 Nested Dictionary (Dictionary inside Dictionary)

students = {
    "101": {"name": "Alice", "marks": 85},
    "102": {"name": "Bob", "marks": 90}
}
print(students["102"]["name"])   # Output: Bob

🧠 Real-Life Analogy

A dictionary is like a contact list:

  • Name (key)Phone number (value)

  • Each contact is unique, and you use the name to fetch the number.


✅ Summary

  • Dictionaries store key-value pairs.

  • Keys must be unique and immutable.

  • Great for structured data like JSON, user profiles, records, etc.