PYTHON

Python Dictionary: Syntax and Examples [Python Tutorial]

In Python, a dictionary (or dict) is a built-in data type for storing data in key-value pairs. While keys have to be immutable (e.g., integers or strings), values can have any type, including lists or other dictionaries.

How to Use Python Dictionaries

Python’s dictionary syntax is straightforward (unlike other programming languages like Java). You can use a dictionary in a few different ways: creating the dictionary and accessing, adding, and modifying values.

Creating a Dictionary in Python

The syntax to create a new dictionary in Python requires curly braces ({}). Within the curly braces, you add key-value pairs with a colon in between. After each key-value pair, you add a comma (except after the last key-value pair).

employee_dict = {
	"name": "Alice",
	"age": 30,
	"role": "Engineer"
}
  • employee_dict: The variable to store the dictionary.
  • "name", "age", "role": The unique and immutable keys for the dictionary.
  • "Alice", 30, "Engineer": The corresponding values for the keys.

You can create (or initialize) an empty dictionary by assigning opening and closing curly braces to a variable. Since dictionaries are mutable, you can add key-value pairs at any time.

employee_dict = {}

Accessing Dictionary Values

You can access dictionary values like lists and indices by referencing their keys within square brackets ([]).

print(employee_dict["name"]) # Outputs: Alice

To avoid raising a KeyError if a key doesn't exist, you can use the dict.get() method, which returns None (or a default value parameter) if the key is missing.

print(employee_dict.get("email", "Not available")) # Outputs: Not available

Modifying and Adding Dictionary Values

You can use an assignment (=) to add or modify a value in a dictionary or add a new key-value pair. To modify an existing value, simply use its associated key. To append a new value, assign it to a key not yet present in the dictionary.

employee_dict["age"] = 31 # Update an existing key

employee_dict["email"] = "alice@example.com" # Add a new key-value pair

Removing Dictionary Values

Python provides multiple ways to delete key-value pairs from a dictionary.

The del statement removes a specific key-value pair by referencing the key. If no such key exists, however, the program raises a KeyError.

# Removing a key-value pair with del
employee_dict = {"name": "Alice", "age": 30, "role": "Engineer"}
del employee_dict["role"]  # Deletes the 'role' key-value pair
print(employee_dict)  # Outputs: {'name': 'Alice', 'age': 30'}

The pop() method removes a key-value pair and returns the value associated with the specified key. This is a safer option compared to del because it lets you specify a default value to return if the key is missing.

# Removing a key-value pair with pop()
employee_dict = {"name": "Alice", "age": 30, "role": "Engineer"}
role = employee_dict.pop("role")
print(role)  # Outputs: Engineer
print(employee_dict)  # Outputs: {'name': 'Alice', 'age': 30}

When to Use Python Dictionaries

In Python programming, working with dictionaries is essential for beginners and professional software developers. Dictionaries are the perfect data structure to map unique keys to values.

Storing Configuration Settings

Dictionaries are great for storing app configurations. An app can easily access settings like themes, font sizes, or booleans like autosave preferences using a dictionary.

config = {
    "theme": "dark",
    "font_size": 14,
    "autosave": True
}

Counting Occurrences

You can use a dictionary to count occurrences, such as how often words appear in a text.

word_count = {}
text = "hello hello world"
for word in text.split():
    word_count[word] = word_count.get(word, 0) + 1
print(word_count)  # Outputs: {'hello': 2, 'world': 1}

Handling JSON Data

Dictionaries are ideal for handling JSON data since JSON objects map directly to dictionaries.

import json
json_data = '{"name": "Alice", "age": 30}'
data = json.loads(json_data)
print(data)  # Outputs: {'name': 'Alice', 'age': 30}

Analyzing Data Sets

In data science and machine learning, dictionaries can help you work with data in combination with libraries like pandas. For example, you can convert a dictionary of lists to a pandas DataFrame and analyze the data set.

import pandas as pd

# Dictionary of customer purchase data
data = {
    "CustomerID": [101, 102, 103],
    "PurchaseAmount": [250.75, 320.60, 150.40],
    "Location": ["New York", "Los Angeles", "Chicago"]
}

# Convert dictionary to pandas DataFrame
df = pd.DataFrame(data)
print(df)

Examples of Using Python Dictionaries

E-commerce Platforms

An e-commerce platform might use dictionaries to manage inventory by tracking products and their stock levels.

inventory = {
    "laptop": 10,
    "smartphone": 25,
    "tablet": 15
}
inventory["smartphone"] -= 1  # Selling one smartphone
print(inventory["smartphone"])  # Outputs: 24

Social Media Platforms

A social media platform might use dictionaries to handle API responses with user profiles. Each key could be a user's unique ID, and each value could be a dictionary with more information about that user.

api_response = {
    "status": "success",
    "data": {
        "user_id": 101,
        "user_name": "John Doe",
        "logged_in": False
    }
}
print(api_response["data"]["user_name"])  # Outputs: 'John Doe'

Learn More About Python Dict

Python Dictionary Methods

Dictionaries come with several built-in methods. Some common ones include:

  • The dict get() method returns the value for the specified key if it exists. Otherwise, it returns a default value.
  • With the update() method, you can merge a dictionary with another dictionary or key-value pairs.
  • The dict keys() method returns a dictionary's list of keys as a view object.
  • Similarly, values() returns an array with all the values in the dictionary.
  • Using the items() method, you can get a list of key-value pairs as tuples.
  • The popitem() method removes and returns the last inserted key-value pair from a dictionary.

Python Dictionary of Dictionaries

You can create a dictionary of dictionaries to represent more complex structures. Nested dictionaries can be particularly powerful with hierarchical data, such as a company's departments and employees.

users = {
    "user1": {"name": "Alice", "age": 30},
    "user2": {"name": "Bob", "age": 25}
}
print(users["user1"]["name"])  # Outputs: 'Alice'

Creating a Dictionary from Lists

Using the zip() function, you can create a dictionary from two or more lists of the same length. In case of duplicate keys, only the last occurrence becomes a key-value pair in the dictionary.

keys = ["name", "age", "role"]
values = ["Bea", 28, "Manager"]

# Using zip() to create a dictionary
employee_dict = dict(zip(keys, values))
print(employee_dict)

Merging Dictionaries (Dict + Dict in Python)

To merge dictionaries, you can use the update() method or the unpacking operator (**). Merging dictionaries can help you combine data from different sources.

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

# Using update() method
dict1.update(dict2)
print(dict1)  # Outputs: {'a': 1, 'b': 3, 'c': 4}

# Using ** operator
merged_dict = {**dict1, **dict2}
print(merged_dict)  # Outputs: {'a': 1, 'b': 3, 'c': 4}

Sorting a Dictionary by Value in Python

By default, dictionaries in Python are unordered. Using the built-in function sorted(), you can generate a sorted copy of a dictionary. The dictionary you pass as an argument to sorted() remains unchanged.

grades = {"Alice": 88, "Bob": 75, "Charlie": 93}
sorted_grades = dict(sorted(grades.items(), key=lambda item: item[1]))
print(sorted_grades)  # Outputs: {'Bob': 75, 'Alice': 88, 'Charlie': 93}

Python dict() Constructor

You can also create a dictionary using the dict() function and passing key-value pairs as keyword arguments. Using dict() without any arguments creates an empty dictionary.

employee_dict = dict(name="Alice", age=30, role="Engineer")

Apart from creating dictionaries, the dict() function is ideal for converting a list of tuples into a dictionary. Such conversions can be ideal for transforming data structures like CSV files.

# Converting a list of tuples to a dictionary
pairs = [("name", "Bob"), ("age", 25), ("city", "Los Angeles")]
person = dict(pairs)
print(person)  # Outputs: {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}

Python Iterating Over Dictionaries

When you only need to access a dictionary's keys, you can iterate over the dictionary with a for loop.

my_dict = {"name": "Alice", "age": 30, "city": "New York"}

for key in my_dict:
    print(key)
# Outputs:
# name
# age
# city

When you only need the values without the keys, you can use a for loop with the values() method.

my_dict = {"name": "Alice", "age": 30, "city": "New York"}

for value in my_dict.values():
    print(value)
# Outputs:
# Alice
# 30
# New York

The items() method allows you to iterate over keys and values simultaneously. Using items() can help you access or modify multiple dictionary entries.

my_dict = {"name": "Alice", "age": 30, "city": "New York"}

for key, value in my_dict.items():
    print(f"{key}: {value}")
# Outputs:
# name: Alice
# age: 30
# city: New York

Dictionary Comprehension in Python

Similar to list comprehension, dictionary comprehension is a concise way to create dictionaries in a single line of code. By defining a key-value pair in the format {key: value for item in iterable}, Python iterates over the sequence and populates the dictionary.

squares = {x: x*x for x in range(6)}
print(squares)  # Outputs: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Creating a Dictionary with Default Values

In Python, you can create dictionaries with default values for all keys, which is useful when you need data structures with predictable defaults. You can use the built-in function fromkeys() to create a new dictionary where each key from a collection (e.g., a list) gets the same default value.

# Creating a dictionary with default values
keys = ["name", "age", "role"]
default_dict = dict.fromkeys(keys, "Unknown")
print(default_dict)  # Outputs: {'name': 'Unknown', 'age': 'Unknown', 'rol

The setdefault() method retrieves a value from a dictionary and adds the key with a default value if it doesn’t exist. This eliminates the need for explicit error handling.

# Using setdefault() to fetch or insert a key
employee_dict = {"name": "Alice", "age": 30}
employee_dict.setdefault("role", "Engineer")  # Adds 'role' with default value
print(employee_dict)
# Outputs: {'name': 'Alice', 'age': 30, 'role': 'Engineer'}

Errors in Dictionaries

Python dictionaries are powerful, but improper usage can result in errors. For example, accessing a non-existent key raises a KeyError. To avoid this, you can use the get() method or handle the error using a try...except block.

# Using try-except to handle KeyError
employee_dict = {"name": "Alice", "age": 30}
try:
    print(employee_dict["salary"])
except KeyError as e:
    print(f"KeyError encountered: {e}")
# Outputs: KeyError encountered: 'salary'

Also, using a mutable type as a dictionary key produces a TypeError.

# Attempting to use a mutable key
try:
    invalid_dict = {["key"]: "value"}
except TypeError as e:
    print(f"TypeError: {e}")
# Outputs: TypeError: unhashable type: 'list'
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH