DEV Community

SameerQaisar17
SameerQaisar17

Posted on

Python Dictionaries: The Beginner's Guide

πŸ“Œ Quick Info

  • Topic: Dictionaries in Python
  • Target Audience: Beginners who know lists and loops
  • Goal: Understand how to store and look up data by key

1. Introduction

"Lists let me store many items. But what if I want to find something by name instead of position? That's when I learned about dictionaries β€” and now they're my favorite data structure."

2. The Problem (Without Dictionaries)

names = ["Ali", "Sara", "Ahmed"]
ages = [25, 30, 28]

# To find Ali's age, I have to:
index = names.index("Ali")
print(ages[index])
Enter fullscreen mode Exit fullscreen mode

Problem: Two Lists, manual lookup, easy to mess up.

3. The Solution (With Dictionaries)

people = {
    "Ali": 25,
    "Sara": 30,
    "Ahmed": 28
}

print(people["Ali"])
Enter fullscreen mode Exit fullscreen mode

Output:

25
Enter fullscreen mode Exit fullscreen mode

4. How It Works (Line By Line)

Line 1-5: A dictionary with curly braces. Each entry has a key(name) and a value(age).

Line 7: people[’’Ali’’] looks up the value for the key β€œAli”.

5.Common Dictionary Operations

person = {"name": "Ali", "age": 25}

person["city"] = "Karachi"

print(person.get("country", "Unknown"))  # Unknown

for key, value in person.items():
    print(f"{key}: {value}")
Enter fullscreen mode Exit fullscreen mode

Output:

name:Ali
age: 25
city:Karachi
Enter fullscreen mode Exit fullscreen mode

6. Real Examples (My Practice)

scores = {"Ali": 85, "Sara": 92, "Ahmed": 78}

top_student = max(scores, key=scores.get)
print(f"Top student: {top_student} with {scores[top_student]}")
Enter fullscreen mode Exit fullscreen mode

Output:

Top student: Sara with 92
Enter fullscreen mode Exit fullscreen mode

7. What I learned

  • Dictionaries store key-value pairs.
  • keys must be unique.
  • [ ] accesses a value- throws error if key doesn't exist.
  • .get() returns a default instead of throwing an erroring.
  • .items() loops through both keys and values.

8.Conclusion

β€œDictionaries felt weird at first with all the curly braces. But once I used them to store real data, I never went back. They're the fastest way to lookup information by name.”

Top comments (0)