Python Dictionaries: Organizing Data with Key-Value Pairs

Lesson Overview

Learn Python dictionaries - a powerful data structure that stores information using key-value pairs, just like a real-world phone book or dictionary. Master creating, accessing, and modifying dictionary data with practical examples that make data organization intuitive and efficient.

Lesson Content

Understanding Dictionaries: Real-World Connection

Imagine you have student information scattered across different pages - names on one page, ages on another, and ID card numbers on yet another page - every time you need complete information about one student, you'd have to flip through multiple pages and match positions, which is cumbersome and error-prone, just like how storing data in separate lists makes access difficult and inefficient. Dictionaries solve this by keeping each student bio-da (name, age, ID) is organized together in one page with clear labels, making it instantly accessible and meaningful without the hassle of cross-referencing multiple lists/pages.

Another Analogy is that its like having a physical phone book. You look up someone's name (the key) to find their phone number (the value). Or think of a real dictionary where you look up a word (key) to find its meaning (value). Python dictionaries work exactly the same way! They store data in key-value pairs where:

  • Key: The label you use to find information (like a name or word)
  • Value: The actual information stored (like a phone number or definition) 

Dictionary Creation Accessing Dictionary Data

Dictionaries are created using curly braces { } with key-value pairs separated by colons

To retrieve values from a dictionary, you can use square brackets [] with the key name for direct access, or use the get() method for safer access that won't crash your program if the key doesn't exist."

# Restaurant menu Creation
# dict_variable = { 'key1' : value1 , 'key2' : value2}
menu = {
    "burger": 250,
    "pizza": 400,
    "pasta": 300,
    "salad": 150,
    "coffee": 80
}
# Accessing values using keys
print(f"Burger costs: ₹{menu['burger']}")     # Output: Burger costs: ₹250
print(f"Pizza costs: ₹{menu['pizza']}")       # Output: Pizza costs: ₹400
# Safe way using get() method
price = menu.get("ice_cream")
print(price)                                  # Output: None (no error!)
coffee_price = menu.get("coffee")
print(coffee_price)                           # Output: 80

Dictionary vs List: When to Use What

Accessing Dictionary Data

Tags: python

💬 Comments (2)

Hima Varshini
Hima Varshini 11 hours, 39 minutes ago
Hey, the Dictionary concept is good but it's pretty much like the normal textbook type. If possible can you pls add some more realtime examples, explaining the concept to understand for a commoner.
ByLearning
ByLearning 10 hours, 23 minutes ago
↳ @Hima Varshini
Sure