Python Dictionaries Explained

➡️ 1. What is a Dictionary in Python?

In our previous guide, we explored how lists work by tracking a simple line of data using position numbers (0, 1, 2...). However, sequential numbering isn't always the best way to model real-world details. For instance, if you want to store information about a user profile, mapping an age to index 1 or an email address to index 2 is easy to forget and makes your code confusing.

To solve this, Python gives us a structure called a Dictionary. A dictionary is an unordered, changeable collection that maps distinct labels to specific pieces of information. It uses Key-Value Pairs wrapped inside curly braces { }. Instead of a position index number, you look up data by using its customized "Key" label, just like looking up a word's definition inside a physical language dictionary.

➡️ 2. Creating a Dictionary

To define a dictionary, use a colon : to bind each Key to its matching Value, and separate separate pairs using commas. Keys must be text strings or numbers, while values can hold absolutely anything.

# Storing structured data about a web server configuration
server_status = {
    "host": "127.0.0.1",
    "port": 8080,
    "is_active": True,
    "users_online": 342
}

# Outputting the entire dictionary configuration block
print(server_status)

➡️ 3. Fetching Value Data Safely

To read information back out of your dictionary container, write the name of the dictionary followed by the specific Key wrapped inside traditional square brackets.

Alternatively, Python provides a safer method named .get(). This built-in function is highly recommended for backend development because it keeps your application from crashing if the label you are searching for is completely missing.

app_user = {"username": "cyber_ninja", "level": 42}

# Method A: Direct Bracket Lookup
print(app_user["username"]) # This outputs: cyber_ninja

# Method B: The Safe .get() Function
print(app_user.get("level")) # This outputs: 42
print(app_user.get("email")) # This outputs: None (No crash!)

➡️ 4. Modifying and Adding Key-Value Data

Dictionaries are fully mutable. To update an existing record or append a completely new asset to the data pool, use the exact same assignment syntax structure. If the Key label already exists, Python automatically overwrites the old data. If it doesn't find the label, it generates a brand-new pair.

player_inventory = {"gold": 100, "weapon": "Iron Sword"}

# 1. Updating an existing value data asset
player_inventory["gold"] = 250 

# 2. Inserting a brand-new descriptive key-value item
player_inventory["shield"] = "Wooden Shield"

print(player_inventory) 
# Outputs: {'gold': 250, 'weapon': 'Iron Sword', 'shield': 'Wooden Shield'}

➡️ 5. Crucial Mistakes to Sidestep

Working with complex keys requires following a few strict development parameters:

➡️ 6. Hands-On Dictionary Practice

Let's lock in this knowledge! Open your text editor and complete this short practice challenge: Create a dictionary variable named smart_phone containing three key-value pairs mapping properties for "brand", "model", and "storage_gb". Write a line of code that updates the storage value to a higher number. Finally, append a new key named "5g_supported" set to a Boolean value (True or False) and print out the dictionary.

Conditional statements