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 must 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 Python 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 Python 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 Python Dictionary Values

You can use an assignment (=) to add or modify a value in a Python 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

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, allowing easy access to settings like theme, font size, or booleans like autosave preferences.

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

Counting Occurrences

You can use a Python 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 Python 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 Python dictionary get() method returns the value for the specified key if it exists. Otherwise, it returns a default value.
  • With the dict 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, dict.values() returns an array with all the values in the dictionary.
  • items() returns a list of key-value pairs as tuples.

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, Python dictionaries 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 initialize 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

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

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

Dictionary comprehension allows you to create dictionaries with a single short statement. This method is similar to list comprehensions but for dictionaries.

squares = {x: x*x for x in range(6)}
print(squares)  # Outputs: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
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