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

AspectListsDictionaries
Access MethodBy index position (0, 1, 2...)By key name
OrderingAlways ordered by positionOrdered by key(Python 3.7+)
Best ForSequential data, collectionsLabeled data, relationships
Example UseShopping list, test scoresStudent record, phone book
Access SpeedSlower for large dataVery fast lookups

Accessing Dictionary Data

There are two main ways to read data from dictionaries, each with different behaviours:

Method 1: Using Square Brackets [ ]


menu = {"burger": 250, "pizza": 400, "pasta": 300}
# Direct access - fast and straightforward
burger_price = menu["burger"]
print(f"Burger costs: ₹{burger_price}")  # Output: Burger costs: ₹250
# But be careful! This will crash if key doesn't exist
ice_cream_price = menu["ice_cream"]  # KeyError! > as the ice_cream is not exist in our dict

Method 2: Using .get() Method


menu = {"burger": 250, "pizza": 400, "pasta": 300}
# Safe access - never crashes
burger_price = menu.get("burger")
print(f"Burger price: ₹{burger_price}")  # Output: Burger price: ₹250
# Returns None if key doesn't exist (no crash!)
ice_cream_price = menu.get("ice_cream")
print(f"Ice cream price: {ice_cream_price}")  # Output: Ice cream price: None

Key Differences: [ ] vs .get()

AspectSquare Brackets [ ].get() Method
SpeedSlightly fasterSlightly slower
SafetyCrashes with KeyError if key missingNever crashes, returns None
Default ValuesNot supportedCan provide custom default
Best ForWhen you're sure key existsWhen key might not exist
Exampleprice = menu["burger"]price = menu.get("burger", 0)

 

Coming Up Next

You'll learn how to automatically process every item in your lists and dictionaries, making your programs incredibly powerful and efficient!

Loops are where programming becomes truly powerful - get ready to automate tasks that would take hours to do manually! 🔥

Topics: python