sec02 - dict Overview

dict (dictionary) is a data structure that associates keys with values for management.

スポンサーリンク

How to Initialize a dict (dictionary) in Python

First, let’s initialize a minimal dict. Write the code as follows:

my_profile = {}

Connect the variable name and curly braces {} with an equals sign. This creates an empty dict.

A dict does not have to contain elements. After defining an empty dict, you can add elements using methods like setdefault(). (How to add elements will be explained in detail in a dedicated lecture.)

A dict can hold one or more pairs of key and value. You can initialize a dict as follows:

# Defining on a single line
my_profile = {'name': 'Nico', 'age': 10}

# Defining across multiple lines
my_profile = {
    'name': 'Nico',
    'age': 10
}

The above code initializes a dict. Elements are linked with key: value pairs separated by a colon (:). If there are multiple key: value pairs, separate them with commas (,).

Data Types Usable as Keys and Values in a Python dict

A key is not limited to strings — you can use numbers, tuples, or any data type that itself cannot be modified. For example, you can add elements like 1: 'one' or (1,): 'num_tuple'. You cannot use mutable data types like lists as keys.

Also, a single dict cannot contain multiple identical keys. Each key must be unique.

key_sample = {
    1: 'one',
    (1,): 'num_tuple',
    '1': 'num_str'
}

Although data types other than strings can be used as keys, in most cases you will use strings. Assigning string keys that describe what the values represent is helpful during development and debugging.

There are no restrictions on the data types you can assign to values. You can assign numbers, strings, lists, dicts, or any other data types.

my_profile = {
    'name': 'Nico',
    'age': 10,
    'languages': ['Python', 'Java', 'C', 'C++'],
    'friends': [
        {
            'name': 'Emma',
            'age': 9
        },
        {
            'name': 'Jack',
            'age': 11
        }
    ]
}
スポンサーリンク

Key Order Behavior and Cautions in Python dict

The order of keys in a dict is maintained in the order in which they were defined or added. However, in versions of Python prior to 3.7, key order in a dict is not guaranteed, so care must be taken.

(If you need to develop in environments using versions earlier than Python 3.7, you must write code assuming that key order is not guaranteed.)

How to Retrieve Elements from a Python dict

You can retrieve elements from a dict using syntax like var[key]. Let’s retrieve elements from the my_profile variable used earlier:

my_profile = {
    'name': 'Nico',
    'age': 10,
    'languages': ['Python', 'Java', 'C', 'C++'],
    'friends': [
        {
            'name': 'Emma',
            'age': 9
        },
        {
            'name': 'Jack',
            'age': 11
        }
    ]
}

print(my_profile['name'])      # Nico
print(my_profile['age'])       # 10
print(my_profile['languages']) # ['Python', 'Java', 'C', 'C++']
print(my_profile['friends'])   # [{'name': 'Emma', 'age': 9}, {'name': 'Jack', 'age': 11}]

As shown above, you can retrieve elements using their keys.

However, specifying a key that does not exist will raise an error. You can avoid this by using the get() method. When you are unsure whether the dict contains the desired key, use var.get(key) instead of var[key].

(Dict methods are explained in detail in a dedicated lecture.)

Using len() to Get the Number of Elements in a Python dict

To check how many elements (number of keys) a dict has, use the len() function.

my_profile = {
    'name': 'Nico',
    'age': 10,
    'languages': ['Python', 'Java', 'C', 'C++'],
    'friends': [
        {
            'name': 'Emma',
            'age': 9
        },
        {
            'name': 'Jack',
            'age': 11
        }
    ]
}
print(len(my_profile))  # 4

Even if a value contains nested dicts or lists, the number returned by len() is based on the number of keys.

Handling Nested dicts in Python

To access information in a nested dict, specify the desired keys in sequence, similar to lists. For example, to retrieve Jack’s “age” from the my_friends variable in the code below, write my_friends['Jack']['age'].

my_friends = {
    'Emma': {'age': 9, 'phone': '090-1234-5678'},
    'Jack': {'age': 11, 'phone': '080-1234-5678'}
}
print(my_friends['Jack']['age'])  # 11

How to Format and Display dicts Nicely with Python pprint

When a dict has many elements or is nested, the output from the print() function can be hard to read. In such cases, using the pprint() function improves readability. Let’s compare the output of the my_profile data using print() and pprint(). To use pprint(), you need to write from pprint import pprint as a prerequisite (this is explained in the “Modules” lecture).

from pprint import pprint

my_profile = {
    'name': 'Nico',
    'age': 10,
    'languages': ['Python', 'Java', 'C', 'C++'],
    'friends': [
        {
            'name': 'Emma',
            'age': 9
        },
        {
            'name': 'Jack',
            'age': 11
        }
    ]
}

print(my_profile)
pprint(my_profile)

The output will be as follows:

# Example output of print
{'name': 'Nico', 'age': 10, 'languages': ['Python', 'Java', 'C', 'C++'], 'friends': [{'name': 'Emma', 'age': 9}, {'name': 'Jack', 'age': 11}]}

# Example output of pprint
{'age': 10,
 'friends': [{'age': 9, 'name': 'Emma'}, {'age': 11, 'name': 'Jack'}],
 'languages': ['Python', 'Java', 'C', 'C++'],
 'name': 'Nico'}

While print() can handle this amount of data, in real-world projects where large amounts of data must be analyzed, a single-line print() becomes insufficient. Knowing how to output data with pprint() will be useful in the future.

pprint Output Order

By default, pprint() outputs dict data with keys sorted in alphabetical order. (This only affects how the data is displayed; the original data is not modified.)

If you want to output data in the order managed by the original dict, add the option sort_dicts=False. Writing it like this will output the dict as it is stored:

pprint(my_profile, sort_dicts=False)
Caution

The sort_dicts=False option for pprint() is available only in Python 3.8 and later. To confirm the order of keys in versions earlier than 3.8, you have two options. (Note: In any case, for Python versions earlier than 3.7, the order of dict keys is not guaranteed.)

  1. Use print()
    • Since print() outputs according to key order, it’s simpler to use when dealing with small datasets.
  2. Use code like the following:
for key in my_profile:
    print(key)

(In the above example, the dict’s keys are retrieved in order and printed. For loops are explained in a dedicated lecture.)

スポンサーリンク