Skip to main content

Dictionaries (Part 1): Key-value pairs, creating dictionaries, accessing values

After exploring the ordered worlds of lists and tuples, we now dive into one of Python's most powerful and flexible data structures: the dictionary. Unlike lists and tuples which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type.


📚 Prerequisites

Before we begin, please ensure you have a solid grasp of the following concepts:

  • Basic Python syntax (variables, data types)
  • Understanding of Python lists and tuples.

🎯 Article Outline: What You'll Master

In this article, you will learn:

  • Foundational Theory: The concept of key-value pairs.
  • Core Implementation: How to create dictionaries using curly braces {} and the dict() constructor.
  • Accessing Data: How to retrieve values from a dictionary using their keys.
  • Practical Application: Building a simple program to manage a user profile.

🧠 Section 1: The Core Concepts of Python Dictionaries

A dictionary is a collection that is unordered, mutable, and stores data in key-value pairs.

Key Principles:

  • Key-Value Pairs: This is the heart of a dictionary. Each item in a dictionary consists of a key and a corresponding value. Think of a real-world dictionary: the word is the key, and its definition is the value.
  • Unordered: Before Python 3.7, dictionaries were unordered. From Python 3.7 onwards, they are officially ordered, meaning they remember the insertion order of items. However, you should still think of them as collections you access by key, not by position.
  • Mutable: You can add, remove, and change the key-value pairs in a dictionary after it has been created.
  • Unique Keys: A dictionary cannot have two keys that are the same. Each key must be unique.

💻 Section 2: Deep Dive - Creating Dictionaries

Let's explore the common ways to create a dictionary in Python.

2.1 - Creating Dictionaries with Curly Braces {}

The most common way to create a dictionary is by placing comma-separated key: value pairs inside curly braces {}.

# CodeBlock1.py
# Creating dictionaries with curly braces

# An empty dictionary
empty_dict = {}
print(f"An empty dictionary: {empty_dict}")

# A simple dictionary
student = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
print(f"A student dictionary: {student}")

Step-by-Step Code Breakdown:

  1. empty_dict = {}: We create an empty dictionary using empty curly braces.
  2. student = { ... }: We create a dictionary representing a student.
    • "name" is a key, and its value is "Alice".
    • "age" is a key, and its value is 21.
    • Each key is separated from its value by a colon :, and the pairs are separated by commas.

2.2 - Using the dict() Constructor

You can also create a dictionary using the built-in dict() constructor.

# CodeBlock2.py
# Using the dict() constructor

# Creating a dictionary from keyword arguments
person = dict(name="Bob", age=30, city="New York")
print(f"Dictionary from kwargs: {person}")

# Creating a dictionary from a list of tuples
employee_data = [
("id", 123),
("department", "Engineering")
]
employee = dict(employee_data)
print(f"Dictionary from list of tuples: {employee}")

Walkthrough:

  • dict(name="Bob", ...): When using keyword arguments, the argument names become the keys (as strings), and the argument values become the dictionary values.
  • dict([("id", 123), ...]): You can provide the dict() constructor with an iterable of key-value pairs, such as a list of tuples.

🛠️ Section 3: Accessing Values in a Dictionary

You retrieve values from a dictionary by referring to their key.

3.1 - Accessing with Square Brackets []

This is the most direct way to access a value.

# AccessingExample1.py
# Accessing values with square brackets

student = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}

student_name = student["name"]
print(f"Student's name: {student_name}")

# This will cause an error!
# print(student["gpa"])

Key Point: If you try to access a key that does not exist in the dictionary, Python will raise a KeyError. This can crash your program if not handled properly.

3.2 - Safely Accessing with the .get() Method

To avoid KeyError, you can use the .get() method. It's a safer way to access values.

# AccessingExample2.py
# Accessing values with the .get() method

student = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}

# Get the value for the 'major' key
major = student.get("major")
print(f"Student's major: {major}")

# Try to get a key that doesn't exist
gpa = student.get("gpa")
print(f"Student's GPA: {gpa}") # Output: None

# Provide a default value if the key is not found
gpa_with_default = student.get("gpa", "Not available")
print(f"Student's GPA with default: {gpa_with_default}")

Walkthrough:

  • student.get("major"): This retrieves the value for the key "major".
  • student.get("gpa"): Since the key "gpa" does not exist, .get() returns None by default instead of raising an error.
  • student.get("gpa", "Not available"): You can provide a second argument to .get() which will be returned as the default value if the key is not found.

✨ Section 4: Project-Based Example: User Profile

Let's use a dictionary to create and display a simple user profile.

# ProjectExample.py
# The full Python code for the mini-project.

# Create a user profile dictionary
user_profile = {
"username": "py_dev",
"email": "[email protected]",
"followers": 1500,
"is_active": True
}

# Access and display the user's information
print("--- User Profile ---")
print(f"Username: {user_profile.get('username')}")
print(f"Email: {user_profile.get('email')}")
print(f"Followers: {user_profile.get('followers')}")

# Check for a key that might not exist
location = user_profile.get('location', 'Unknown')
print(f"Location: {location}")
print("--------------------")

💡 Conclusion & Key Takeaways

Dictionaries are the perfect tool for storing data that has a clear relationship between a key and a value. Their flexibility and efficiency make them one of the most used data structures in Python.

Let's summarize the key Python takeaways:

  • Dictionaries store data in key: value pairs.
  • They are created with {} or the dict() constructor.
  • Use square brackets [key] for direct access, but be aware of KeyError.
  • Use the .get(key, default) method for safe access to avoid errors.

Challenge Yourself (Python Edition): Create a dictionary to represent a simple product in an e-commerce store. It should have keys for product_id, name, price, and in_stock (a boolean). Then, print out a formatted description of the product using the .get() method.


➡️ Next Steps

Now that you know how to create and access dictionaries, the next step is to learn how to modify them. In the next article, "Dictionaries (Part 2): Dictionary methods and dictionary comprehensions", we'll explore how to add, update, and remove key-value pairs.

Keep practicing, keep exploring, and enjoy your Python coding adventure!


Glossary (Python Terms)

  • Dictionary: An unordered (in older Python versions) and mutable Python collection of key-value pairs.
  • Key-Value Pair: The combination of a unique key and its associated value that makes up an item in a dictionary.
  • Key: The unique identifier for a value in a dictionary. Must be an immutable type (like a string, number, or tuple).
  • Value: The data associated with a key in a dictionary. Can be of any data type.

Further Reading (Python Resources)