PYTHON

Python Dictionary: The dict() Function, Examples, and More

In Python, a dictionary is a data type that consists of an ordered collection of key-value pairs. Dictionaries work with values of any data type, including numbers, strings, dictionaries, and lists.

How to Use Python Dictionaries

Creating Python Dictionaries

To create a dictionary in Python, you can use curly braces ({}) and add key-value pairs separated by colons and commas.

my_dict = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}
  • my_dict: The name of the dictionary.
  • "key1", "key2", "key3": Dictionary keys (unique identifiers for values).
  • "value1", "value2", "value3": Values associated with each key.

Accessing Values

Similar to lists and indices, you can access the value of a key-value pair using the key within square brackets ([]).

value1 = my_dict["key1"]
print(value1)  # Outputs: 'value1'

Modifying and Adding Values

You can add a new key-value pair or update an existing value by referencing the key.

# Adding a new key-value pair
my_dict["key4"] = "value4"
print(my_dict)

# Modifying an existing value
my_dict["key2"] = "new_value2"
print(my_dict)

When to Use Python Dictionaries

Dictionaries are ideal when you need a data structure that can map unique keys to values.

Storing Configuration Settings

You can use dictionaries to store configuration settings and preferences. This method allows for easy access and modification of settings.

config = {
    "theme": "dark",
    "font_size": 14,
    "autosave": True
}
print(config["theme"])  # Outputs: 'dark'

Counting Occurrences

Dictionaries are great for counting occurrences of items, such as word frequencies in 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. This makes it easy to parse and manipulate JSON data.

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

Examples of Using Python Dictionaries

Dictionaries are common in web development, data science, and many other fields.

Managing Inventory

E-commerce platforms use dictionaries to manage and track inventory, updating stock levels as necessary.

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

Storing API Responses

Many web applications use dictionaries to store parsed API responses for processing and displaying data from APIs.

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

Graph Representations

In data visualization applications, dictionaries can represent graphs, where keys are nodes, and values are lists of adjacent nodes.

graph = {
    "A": ["B", "C"],
    "B": ["A", "D"],
    "C": ["A", "D"],
    "D": ["B", "C"]
}
print(graph["A"])  # Outputs: ['B', 'C']

Learn More About Python Dictionaries

Python Dictionary Methods

Python dictionaries come with a set of built-in methods. Here's an overview of some of the most common dictionary methods:

  • The Python dictionary get() method returns the value associated with a key. You can use the optional default parameter to specify default value to return if the key doesn't exist.
  • The update() method updates a dictionary in Python by inserting the key-value pairs of another dictionary.
  • keys() returns a list of all the dictionary keys as a view object.
  • values() returns a list of all the dictionary values as a view object.
  • The items() method returns a view object with a list of key-value tuple pairs.
  • The pop() method removes a key-value pair from the dictionary and returns its value. You can use the optional default parameter to specify default value to return if the key doesn't exist.

Python dict() Function

Instead of curly braces, you can also use the built-in dict() function to create dictionaries in Python. To create a new dictionary with key-value pairs, you need to pass the keys and values as keyword arguments.

# Creating a dictionary using the dict() function
person = dict(name="Alice", age=30, city="New York")
print(person)  # Outputs: {'name': 'Alice', 'age': 30, 'city': 'New York'}

The dict() function can also convert a list of tuples into a dictionary. This is useful when you need to transform data structures, such as converting CSV data into a dictionary.

# 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'}

Dictionary Comprehension in Python

Dictionary comprehension allows you to create dictionaries in a concise way. 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}

Merging Dictionaries in Python

You can merge multiple dictionaries with the update() method or the unpacking operator (**). This capability simplifies combining data from multiple 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

Using the built-in function sorted(), you can generate a sorted copy of a dictionary. The original dictionary 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 Iterating Over Dictionaries

You can iterate over the keys of a dictionary using a for loop. This is useful when you only need to access the keys.

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

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

To iterate over the values of a dictionary, use the .values() method. This approach is helpful when you only need the values and not the keys.

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 both keys and values simultaneously, which is useful for accessing or modifying 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

Python Dictionary of Dictionaries

Nested dictionaries within dictionaries can help you handle complex data structures. Nesting dictionaries is especially useful with hierarchical data.

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

Converting Python Dictionaries to JSON

You can convert dictionaries to other structures like JSON strings for compatibility with web APIs, e.g. for sending data to a server.

data = {"name": "Alice", "age": 30}
json_data = json.dumps(data)
print(json_data)  # Outputs: {"name": "Alice", "age": 30}
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