πŸ“˜ Python Dictionary β€” Key–Value Data Structure

Introduction 🌟

A dictionary in Python is an unordered collection of key–value pairs. Each key must be **unique**, and it is used to access the associated value. Dictionaries are extremely useful for structured data, configurations, JSON, and fast lookups.

Note

πŸ’‘ Dictionaries use { key: value } syntax and are mutable (changeable).

1. Creating Dictionaries 🧱

create_dict.py

# Empty dictionary
empty_dict = {}

# Dictionary with values
student = {
    "name": "Sathish",
    "age": 25,
    "city": "Chennai"
}

# Using dict() constructor
user = dict(username="admin", password="1234")

# Mixed data types
data = {
    "id": 101,
    "active": True,
    "roles": ["admin", "editor"]
}

2. Accessing Dictionary Values πŸ”‘

access_dict.py

student = {"name": "Sathish", "age": 25}

print(student["name"])      # Sathish
print(student.get("age"))   # 25
print(student.get("city"))  # None (no error)

Note

βœ”οΈ dict["key"] throws an error if key does not exist
βœ”οΈ dict.get() returns None safely

3. Modifying Dictionary Values ✏️

modify_dict.py

student = {"name": "Sathish", "age": 25}

student["age"] = 26
student["city"] = "Chennai"   # Add new key

print(student)

4. Removing Items βž–

pop() β€” Remove by key

pop_key.py

student.pop("age")

popitem() β€” Remove last inserted item

popitem.py

student.popitem()

del β€” Remove key

del_key.py

del student["name"]

clear() β€” Remove all

clear_dict.py

student.clear()

5. Looping Through Dictionaries πŸ”

Loop keys

dict_keys_loop.py

for key in student:
    print(key)

Loop values

dict_values_loop.py

for value in student.values():
    print(value)

Loop key–value pairs

dict_items_loop.py

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

6. Dictionary Methods 🧰

MethodDescription
keys()Returns all keys
values()Returns all values
items()Returns key-value pairs
get()Safe value access
update()Update multiple values
pop()Removes a key
clear()Clears dictionary

7. Using update() to Modify Multiple Values πŸ› οΈ

dict_update.py

student = {"name": "Sathish", "age": 25}

student.update({"age": 26, "city": "Chennai"})
print(student)

8. Nested Dictionaries 🧩

nested_dict.py

students = {
    1: {"name": "Sathish", "age": 25},
    2: {"name": "Kumar", "age": 22}
}

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

9. Dictionary Comprehension ⚑

dict_comprehension.py

squares = {x: x*x for x in range(1, 6)}
print(squares)

Note

βœ”οΈ Makes dictionary creation compact and powerful.

10. Checking If Key or Value Exists πŸ”

dict_membership.py

student = {"name": "Sathish", "age": 25}

print("name" in student)          # True
print("Sathish" in student.values())  # True

11. Real-World Examples 🌍

Storing JSON-like data

json_like.py

product = {
    "id": 101,
    "name": "Laptop",
    "price": 45000,
    "stock": 10
}

Counting frequency of words

word_count.py

sentence = "apple banana apple mango banana apple"
words = sentence.split()

count = {}

for w in words:
    count[w] = count.get(w, 0) + 1

print(count)

Login system

login_system.py

users = {"admin": "1234", "user": "abcd"}

username = input("Enter username: ")
password = input("Enter password: ")

if username in users and users[username] == password:
    print("Login successful")
else:
    print("Invalid credentials")

Conclusion πŸŽ‰

>>β€œDictionaries make data structured, fast, and easy to manage β€” a true powerhouse in Python.” ✨

You now understand Python Dictionaries completely! Want the next topic? Try List Comprehension, Functions, String Methods, or File Handling. Just tell me! 😊