Python Tutorials

Python Dictionaries : Keys, Nested & Methods

If you wanted to look up the definition of the word “Algorithm” in a physical book, you wouldn’t read every single page starting from page one until you found it. You would jump straight to the “A” section, look for the exact word, and read the definition attached to it.

In Python, Lists force us to find data using numerical indexes (0, 1, 2). But what if we want to look up a user’s email address using their username? Or find a product’s price using its barcode? For this, we need a data structure that uses custom labels instead of numbers.

Enter the Dictionary. Dictionaries are one of the most powerful and widely used data structures in Python. They allow you to store and retrieve data instantly using a custom label (the “key”) to unlock a specific piece of data (the “value”). If you plan on doing web development, data science, or API integration, mastering dictionaries is absolutely essential.

What is Dictionaries?

In Python, a Dictionary is a built-in, mutable data structure that stores data in key-value pairs.

  • Key: A unique, immutable identifier (like a string, integer, or tuple) used to look up a value. Keys must be 100% unique within a single dictionary.
  • Value: The data associated with the key. Values can be of any data type (strings, lists, other dictionaries) and can be duplicated.
  • As of Python 3.7, dictionaries maintain the insertion order of their keys, though their primary purpose is rapid, unordered data retrieval via hashing.

Syntax & Basic Usage

Dictionaries are created using curly braces {}. Inside the braces, you define a key, followed by a colon :, followed by its value. You separate multiple key-value pairs with commas.

# Creating a simple dictionary of a user's profile
user_profile = {
    "username": "CodeNinja99",
    "access_level": 5,
    "is_active": True
}

# Accessing a value by referencing its key inside square brackets
current_user = user_profile["username"]

print("The user is:", current_user)

# Expected Output:
# The user is: CodeNinja99
Code language: PHP (php)

Python Dictionary Methods and Operations

Understanding python dictionary methods is crucial for manipulating complex datasets. Let’s explore every major feature, operation, and technique to handle dictionaries effectively.

1. Creating Dictionaries

You can create dictionaries using curly braces or the built-in dict() constructor.

Creating an Empty Dictionary

Often, you will create an empty dictionary to store data that your program generates later.

# Creating an empty dictionary
player_inventory = {}

print("Empty Dictionary:", player_inventory)

# Expected Output:
# Empty Dictionary: {}
Code language: PHP (php)

Using the dict() Constructor

You can also create dictionaries using keyword arguments with the dict() function. Note that when using this method, you do not put quotes around the keys.

# Creating a dictionary using the dict() constructor
server_config = dict(host="localhost", port=8080, secure=True)

print("Server Configuration:", server_config)

# Expected Output:
# Server Configuration: {'host': 'localhost', 'port': 8080, 'secure': True}
Code language: PHP (php)

2. Accessing Data

There are two primary ways to retrieve data from a dictionary. Knowing the difference between them will save your program from crashing.

Direct Key Access (The Bracket Notation)

You can access a value by placing the key inside square brackets []. However, if the key does not exist, Python will throw a fatal KeyError.

employee_data = {"name": "Alice", "department": "HR"}

# Accessing an existing key directly
employee_name = employee_data["name"]

print("Employee Name:", employee_name)

# Expected Output:
# Employee Name: Alice
Code language: PHP (php)

Safe Access (.get())

The .get() method is the safest way to retrieve data. If the key exists, it returns the value. If the key does not exist, it peacefully returns None (or a custom default value) instead of crashing your program.

employee_data = {"name": "Alice", "department": "HR"}

# Accessing a missing key safely
employee_salary = employee_data.get("salary")

# Accessing a missing key safely WITH a custom fallback value
employee_location = employee_data.get("location", "Remote")

print("Salary:", employee_salary)
print("Location:", employee_location)

# Expected Output:
# Salary: None
# Location: Remote
Code language: PHP (php)

3. Adding and Updating Data

Because dictionaries are mutable, you can add new python key value pairs or overwrite existing ones dynamically.

Direct Assignment

If you assign a value to a key that doesn’t exist, Python adds it. If you assign a value to a key that does exist, Python overwrites the old value.

game_settings = {"volume": 50, "difficulty": "Normal"}

# Adding a brand new key-value pair
game_settings["resolution"] = "1920x1080"

# Overwriting an existing key
game_settings["volume"] = 75

print("Updated Settings:", game_settings)

# Expected Output:
# Updated Settings: {'volume': 75, 'difficulty': 'Normal', 'resolution': '1920x1080'}
Code language: PHP (php)

Updating Multiple Items (.update())

The .update() method allows you to merge another dictionary into your current one, adding new keys and updating matching ones simultaneously.

game_settings = {"volume": 50, "difficulty": "Normal"}
new_preferences = {"difficulty": "Hard", "subtitles": True}

# Merges new_preferences into game_settings
game_settings.update(new_preferences)

print("Merged Settings:", game_settings)

# Expected Output:
# Merges Settings: {'volume': 50, 'difficulty': 'Hard', 'subtitles': True}
Code language: PHP (php)

4. Removing Data

Python provides several methods to safely extract or delete data from a dictionary.

Removing by Key (.pop())

The .pop() method removes a specific key and returns its value. You can also provide a default fallback value just in case the key wasn’t there to begin with.

shopping_cart = {"apple": 1.50, "bread": 3.00, "milk": 2.50}

# Removes 'bread' and stores its value (3.00)
removed_item_price = shopping_cart.pop("bread")

print("Cart after pop:", shopping_cart)
print("Price of removed item: $", removed_item_price)

# Expected Output:
# Cart after pop: {'apple': 1.5, 'milk': 2.5}
# Price of removed item: $ 3.0
Code language: PHP (php)

Removing the Last Inserted Item (.popitem())

The .popitem() method removes the very last key-value pair that was added to the dictionary and returns it as a tuple.

shopping_cart = {"apple": 1.50, "bread": 3.00}

# Removes the last inserted item ('bread', 3.00)
last_item = shopping_cart.popitem()

print("Cart after popitem:", shopping_cart)
print("Removed pair:", last_item)

# Expected Output:
# Cart after popitem: {'apple': 1.5}
# Removed pair: ('bread', 3.0)
Code language: PHP (php)

Deleting with del and .clear()

The del keyword permanently deletes a key without returning it. The .clear() method empties the entire dictionary perfectly clean.

shopping_cart = {"apple": 1.50, "bread": 3.00, "milk": 2.50}

# Delete a specific key
del shopping_cart["apple"]
print("After del:", shopping_cart)

# Wipe the dictionary clean
shopping_cart.clear()
print("After clear:", shopping_cart)

# Expected Output:
# After del: {'bread': 3.0, 'milk': 2.5}
# After clear: {}
Code language: PHP (php)

5. Extracting Views (.keys(), .values(), .items())

Sometimes you only want a list of the keys, or only the values. Python provides three “view” methods to peek inside your dictionary.

student_grades = {"Math": "A", "Science": "B", "History": "A"}

# 1. Get only the keys
all_subjects = student_grades.keys()

# 2. Get only the values
all_grades = student_grades.values()

# 3. Get both as a list of tuples
all_pairs = student_grades.items()

print("Keys:", list(all_subjects))
print("Values:", list(all_grades))
print("Pairs:", list(all_pairs))

# Expected Output:
# Keys: ['Math', 'Science', 'History']
# Values: ['A', 'B', 'A']
# Pairs: [('Math', 'A'), ('Science', 'B'), ('History', 'A')]
Code language: PHP (php)

6. Iterating Over Dictionaries

To truly iterate over dictionary python objects, we combine for loops with the view methods we just learned.

Iterating Over Key-Value Pairs

Using .items() allows you to unpack the key and the value into two separate variables during each loop iteration. This is the most common way to loop through a dictionary.

inventory_stock = {"Laptops": 15, "Monitors": 42, "Keyboards": 105}

# Unpacking the Key and Value simultaneously
for product_name, stock_count in inventory_stock.items():
    print(f"We have {stock_count} {product_name} in the warehouse.")

# Expected Output:
# We have 15 Laptops in the warehouse.
# We have 42 Monitors in the warehouse.
# We have 105 Keyboards in the warehouse.
Code language: PHP (php)

7. Nested Dictionaries

You can put dictionaries inside other dictionaries. Nested dictionaries in python are used constantly in web development to parse JSON data from APIs.

# A nested dictionary representing an organization's employees
company_database = {
    "emp_001": {
        "name": "Sarah",
        "role": "Engineer",
        "salary": 95000
    },
    "emp_002": {
        "name": "Mike",
        "role": "Designer",
        "salary": 85000
    }
}

# Accessing deeply nested data requires chaining the keys together
sarah_role = company_database["emp_001"]["role"]
mike_salary = company_database["emp_002"]["salary"]

print("Employee 1 Role:", sarah_role)
print("Employee 2 Salary: $", mike_salary)

# Expected Output:
# Employee 1 Role: Engineer
# Employee 2 Salary: $ 85000
Code language: PHP (php)

Real-World Practical Examples

Scenario 1: Word Frequency Counter

A classic programming scenario is counting how many times a specific word or item appears in a dataset. We can use a dictionary to track the counts dynamically.

# A list of votes for a company mascot
mascot_votes = ["Tiger", "Bear", "Tiger", "Wolf", "Bear", "Tiger"]

# Empty dictionary to hold our tally
vote_tally = {}

for animal in mascot_votes:
    # If the animal is already in our dictionary, add 1 to its count
    if animal in vote_tally:
        vote_tally[animal] += 1
    # If it's the first time seeing this animal, set its count to 1
    else:
        vote_tally[animal] = 1

print("Final Mascot Vote Tally:")
for mascot, total_votes in vote_tally.items():
    print(f"{mascot}: {total_votes} votes")

# Expected Output:
# Final Mascot Vote Tally:
# Tiger: 3 votes
# Bear: 2 votes
# Wolf: 1 votes
Code language: PHP (php)

Scenario 2: API Payload Processing

When you fetch data from a web API (like a weather service), it almost always arrives as a nested dictionary. Here is how you safely extract that data.

# Simulated JSON payload from a weather API
weather_api_response = {
    "location": "Seattle",
    "status": 200,
    "forecast": {
        "temperature": 68,
        "conditions": "Partly Cloudy",
        "humidity": "45%"
    }
}

# Always check if the status is successful before processing
if weather_api_response.get("status") == 200:
    city = weather_api_response["location"]
    # Safely drilling down into the nested dictionary
    temp = weather_api_response["forecast"]["temperature"]
    weather = weather_api_response["forecast"]["conditions"]
    
    print(f"The weather in {city} is {temp} degrees and {weather}.")
else:
    print("Error: Could not retrieve weather data.")

# Expected Output:
# The weather in Seattle is 68 degrees and Partly Cloudy.
Code language: PHP (php)

Best Practices & Common Pitfalls

  • The KeyError Trap: As mentioned, trying to access my_dict["fake_key"] directly will crash your program. Always use my_dict.get("fake_key") if there is even a 1% chance the data might be missing.
  • Immutable Keys Only: You can use strings, integers, floats, and even tuples as dictionary keys. However, you cannot use a List as a dictionary key because lists are mutable (changeable). Python requires keys to be permanently locked in place for its hashing algorithm to work.
  • Avoid Key Duplication: If you try to define a dictionary with two identical keys (e.g., {"color": "red", "color": "blue"}), Python will not throw an error. Instead, it will silently overwrite the first value with the second value. A dictionary can only have one unique instance of any key.
  • Understand the Performance: Why use a dictionary over a list? Speed. Searching a list of 1 million items to find a specific value requires checking every single item one by one (O(n) time). Looking up a value by its key in a dictionary takes the exact same amount of time whether the dictionary has 10 items or 10 million items (O(1) time).

Summary

  • A Dictionary is a mutable data structure that stores data in structured key-value pairs, allowing for lightning-fast data retrieval.
  • Create dictionaries using curly braces {} or the dict() constructor.
  • Use dict[key] for direct access, but heavily prefer .get(key) to safely avoid program-crashing KeyError exceptions.
  • Add or update data by assigning a value to a key, or merge entire dictionaries using the .update() method.
  • Remove data securely using .pop(), .popitem(), or del.
  • Easily iterate over your data using .keys(), .values(), and the highly versatile .items() method.
  • Build nested dictionaries to structure complex data, much like modern JSON files.

Leave a Comment