Python Dictionaries: Complete Guide from Basics to Advanced

1. What is an associative array (dictionary) in Python?

Python’s “associative array” is a data structure that manages data using key‑value pairs. Generally, what is called an “associative array” is provided in Python as the dict type. For example, by using a name as the key and storing age or occupation as the values, data lookup and management become efficient. Here, a “key” is a unique identifier used to specify data, and each key must be unique.

Differences between the dictionary type and other data structures

The hallmark of the dictionary type is fast lookup using keys. Compared with sequence types like Python’s list or tuple, you don’t have to search elements sequentially; you can directly access by key, which dramatically improves lookup speed. Especially when handling large amounts of data or in scenarios where lookups occur frequently, the dictionary type is extremely handy.
# Example of a dictionary
person = {
    "name": "Tanaka",
    "age": 30,
    "occupation": "Engineer"
}
print(person["name"])  # Output: Tanaka

2. How to Create a Python Dictionary

In Python, you can create dictionaries in several ways. You can use literal notation, dict() function, zip() function, etc., choosing the method that fits the situation.

Method Using Literals

Literal notation uses curly braces {} to create a dictionary, and it is the most common and simple method. Using literals lets you define keys and values in a single line, allowing you to create dictionaries intuitively.
# Literal notation
fruit_prices = {
    "apple": 100,
    "banana": 150,
    "orange": 200
}

dict() Function Creation Method

dict() function is useful when generating a dictionary from a list of tuples, etc. This method is especially handy when the data changes dynamically.
# dict function
fruit_prices = dict([("apple", 100), ("banana", 150), ("orange", 200)])

zip() Function Creation Method

When creating a dictionary by matching different lists as keys and values, you can achieve it concisely by using the zip() function. This allows you to efficiently generate a dictionary from the corresponding lists.
# zip function
keys = ["apple", "banana", "orange"]
values = [100, 150, 200]
fruit_prices = dict(zip(keys, values))

3. Basic Dictionary Operations

Python dictionaries are mutable data structures that allow flexible addition, updating, and deletion of data. They also feature faster lookup speeds compared to other data structures.

Adding and Updating Elements

To add or update an element in a dictionary, you simply assign a value to a specified key. Assigning a value to an existing key updates it, while specifying a new key adds a new entry.
fruit_prices = {"apple": 100, "banana": 150}
# Add a new element
fruit_prices["orange"] = 200
# Update an existing element
fruit_prices["apple"] = 120

Deleting Elements

When deleting an element with a specific key, you can use the del statement or the pop() method. The pop() method returns the deleted value, which is useful when you need to retain the removed data.
# Deletion using the del statement
del fruit_prices["banana"]
# Deletion using the pop method (returns the deleted value)
removed_price = fruit_prices.pop("orange")

4. Advanced Operations

Using dictionaries in an advanced way includes merging with other dictionaries and frequency counting. This enables even more sophisticated data manipulation.

Dictionary Merging

When consolidating multiple dictionaries into one, the update() method is useful. If there are duplicate keys, they are overwritten, allowing you to merge or update data in a single step.
dict1 = {"apple": 100, "banana": 150}
dict2 = {"banana": 200, "grape": 300}
dict1.update(dict2)
# Output: {'apple': 100, 'banana': 200, 'grape': 300}

Applying Frequency Counting

Frequency counting is handy, for example, when counting how many times each character appears in a string. Using a dictionary type makes data aggregation and analysis efficient.
text = "apple"
frequency = {}
for char in text:
    if char in frequency:
        frequency[char] += 1
    else:
        frequency[char] = 1
# Output: {'a': 1, 'p': 2, 'l': 1, 'e': 1}
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

5. Looping Through a Dictionary

Looping is ideal for processing all elements of a dictionary at once. This lets you manipulate keys and values individually or retrieve a list of the data.

Getting Keys and Values with a Loop

To process keys, values, or their combinations in a dictionary, you can use the keys(), values(), and items() methods.
fruit_prices = {"apple": 100, "banana": 150, "orange": 200}
# Keys only
for key in fruit_prices.keys():
    print(key)
# Values only
for value in fruit_prices.values():
    print(value)
# Key-value pairs
for key, value in fruit_prices.items():
    print(f"The price of {key} is {value} yen")

6. Summary of Python Dictionaries

Python dictionaries (associative arrays) manage data as key‑value pairs, dramatically improving the efficiency of lookups and operations. Compared to lists and tuples, they offer faster lookups, making them advantageous when handling large amounts of data. They are also well suited for aggregating and analyzing data, and for combining with other data structures, making them indispensable for basic data manipulation in Python. Getting comfortable with dictionary operations enables even more advanced data processing.
年収訴求