Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python - Dictionaries – Complete Guide for Beginners

Python dictionaries are one of the most important built-in data structures used to store data in key-value pairs.

Unlike lists or sets, dictionaries allow you to store data with a meaningful label (key), making data access fast and organized.

Dictionaries are:

  • Ordered (Python 3.7+)
  • Mutable
  • Indexed by keys
  • Do not allow duplicate keys

In this tutorial, you will learn:

  • What dictionaries are
  • How to create and use them
  • Accessing and modifying data
  • Adding and removing items
  • Looping through dictionaries
  • Real-world examples
  • Common mistakes and best practices

What is a Dictionary?

A dictionary stores data in key : value pairs.

Example:

student = {
    "name": "John",
    "age": 20,
    "course": "Python"
}

print(student)

Output:

{'name': 'John', 'age': 20, 'course': 'Python'}

Creating a Dictionary

Method 1: Using curly braces

car = {
    "brand": "Toyota",
    "model": "Corolla",
    "year": 2024
}

Method 2: Using dict() constructor

car = dict(
    brand="Toyota",
    model="Corolla",
    year=2024
)

Access Dictionary Items

You can access values using keys.

student = {
    "name": "Alice",
    "age": 22
}

print(student["name"])

Output:

Alice

Using get() Method (Safe Access)

print(student.get("age"))

If key does not exist:

print(student.get("grade"))

Output:

None

Change Dictionary Items

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

student["age"] = 21

print(student)

Add Dictionary Items

student = {
    "name": "Charlie"
}

student["age"] = 25

print(student)

Remove Dictionary Items

Using pop()

student.pop("age")

Using del

del student["name"]

Using clear()

student.clear()

Loop Through a Dictionary

Loop keys

for key in student:
    print(key)

Loop values

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

Loop key-value pairs

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

Dictionary Methods

Python provides many useful methods:

MethodDescription
keys()Returns all keys
values()Returns all values
items()Returns key-value pairs
get()Safe access
pop()Removes item
popitem()Removes last item
update()Adds/updates items
clear()Removes all items
copy()Copies dictionary

Using keys(), values(), items()

keys()

print(student.keys())

values()

print(student.values())

items()

print(student.items())

Nested Dictionaries

Dictionaries can store other dictionaries.

students = {
    "student1": {
        "name": "Alice",
        "age": 20
    },
    "student2": {
        "name": "Bob",
        "age": 22
    }
}

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

Real-World Example: User Profile

user = {
    "username": "john_doe",
    "email": "john@example.com",
    "active": True
}

print(user["email"])

Real-World Example: Product Inventory

product = {
    "name": "Laptop",
    "price": 1200,
    "stock": 10
}

product["stock"] -= 1

print(product)

Real-World Example: Student Grades

grades = {
    "Alice": 85,
    "Bob": 90,
    "Charlie": 78
}

print(grades["Bob"])

Checking if Key Exists

if "name" in student:
    print("Key exists")

Dictionary Length

print(len(student))

Copy Dictionary

new_student = student.copy()

Merge Dictionaries

Using update()

a = {"x": 1, "y": 2}
b = {"z": 3}

a.update(b)

print(a)

Using | operator (Python 3.9+)

a = {"x": 1}
b = {"y": 2}

result = a | b

print(result)

Common Mistakes

Mistake 1: Using index

student[0]  # Error

Mistake 2: Duplicate keys

data = {"name": "A", "name": "B"}

Only last value is kept.

Mistake 3: Key error

print(student["grade"])  # may error

Use get() instead.


Best Practices

  • Use meaningful keys
  • Use get() for safe access
  • Use dictionaries for structured data
  • Avoid duplicate keys
  • Use items() for looping key-value pairs

Quick Summary

TaskMethod
Create dictionary{} or dict()
Access valuekey or get()
Add itemdict[key] = value
Remove itempop() / del
Loop dictionaryitems()
Copy dictionarycopy()
Merge dictionariesupdate() or ``

Conclusion

Python dictionaries are one of the most powerful and flexible data structures. They allow you to store data in key-value pairs, making data access fast, readable, and efficient.

By mastering dictionaries, you can build real-world applications like user systems, inventory management, APIs, and data processing tools.

Understanding dictionaries is essential for becoming a strong Python developer. 




Post a Comment

0 Comments