Python | Learned the dict type and used it in a for statement

2021-07-03

Hello everyone. This page is an English translation of a Japanese page. (The original Japanese has been slightly rewritten to make it easier to translate into English.)

In Python, there is a type called the dictionary type. This is a type that manages the mapping of keys to values. The official name of the types is Mapping Types in the Python 3.9.4 documentation. In this article, we learned the basic usage of this type and tried to use it in a list that is written in the “in" part of the for statement. This article is a reminder of what I learned from that experience.

For more information about the environment in which Python is running, please refer to the previous article: Installing Miniconda and PyCharm Community Edition on Windows and outputting “Hello World".

Basic usage of the dictionary type

One of the main built-in types in Python is the mapping type. For convenience, we’ll call it the dictionary type. In this article, I have created a sample of how to declare a dictionary and how to get its value.

How to declare and get values

A simple way to declare a dictionary type is to enumerate the “key: value" combinations separated by commas and enclose them in curly brackets.

In the following sample program, we first define an object of type dictionary.

Source
sample_dict = {
    'id': 1,
    'name': 'sample_name_0001'
}

print('key: {0}'.format(sample_dict['id']))

key = 'name'
print('{0}...{1}'.format(key, sample_dict[key]))

This time, we decided to use a string as the key. There are some types that cannot be specified as keys, but strings can. The execution result is as follows.

Execution results
key: 1
name...sample_name_0001

In the first line, we declare a dictionary type object. A dictionary type object with the following combinations will be stored in the variable sample_dict.

key value
id 1
name sample_name_0001

There are several ways to get the value corresponding to a key. In the above, we use the method of specifying the key with a bracket. In the first print statement, the key 'id’ is specified and the value is output. Variables can be used as keys. The second print statement above stores the string in the variable key and specifies it as the key of the dictionary type object sample_dict.

In the method using brackets, an error will occur if a non-existent key is specified.

The following is a sample of the error that occurs.

Source
sample_dict = {
    'id': 1,
    'name': 'sample_name_0001'
}

print(sample_dict['abc'])
Execution results
Traceback (most recent call last):
  File "...A002.py", line 3, in <module>
    print(sample_dict['abc'])
KeyError: 'abc'

In the above, the key “abc" is not defined in sample_dict, so KeyError will be raised.

get() method

The get() method is defined for the dictionary type. The format is as follows

get(key[, default])

Depending on whether or not the parameter “default" is given, the following changes slightly.

If the parameter “default" is not given
  • If the key exists in the dictionary type object, it returns the corresponding value.
  • Otherwise, it will return None.
If the parameter “default" is given
  • If the key exists in the dictionary type object, it returns the corresponding value.
  • Otherwise, it will return default.

Regardless of whether the parameter “default" is given or not, if the argument key exists in the dictionary type object, the value corresponding to key will be returned.

The following is a sample using the get() method.

Source
sample_dict = {
    'id': 1,
    'name': 'sample_name_0001'
}

print(sample_dict.get('abc'))

print(sample_dict.get('abc', 'not found'))

The execution result is as follows.

Execution results
None
not found

The above two print statements specify the key 'abc’, but that key does not exist in the target dictionary type object. In the first print statement, the parameter “default" was not given, so None was returned. In the second print statement, the parameter “default" is given. The string is returned.

Use in a for statement

The syntax of the for statement is as follows.

for variable in [list]:
	Process to be repeated 1
	Process to be repeated 2
	.
	.
	.

In the previous article (Learned about for and while statements), we did not use dictionary types for lists. In this article, we will introduce a method to use dictionary types in list expressions.

To use the value of a dictionary type object in a for statement, the following three methods are provided.

keys()
An object consisting of keys will be returned.
values()
An object consisting of values will be returned.
items()
An object consisting of a key-value pair will be returned.

As for the class name of the returned object, I checked it with the following sample.

Source
sample_dict = {
    'id': 1,
    'name': 'sample_name_0001'
}

v = sample_dict.keys()
print(type(v))
print(v)

print('----------------------------------')

v = sample_dict.values()
print(type(v))
print(v)

print('----------------------------------')

v = sample_dict.items()
print(type(v))
print(v)
Execution results
<class 'dict_keys'>
dict_keys(['id', 'name'])
----------------------------------
<class 'dict_values'>
dict_values([1, 'sample_name_0001'])
----------------------------------
<class 'dict_items'>
dict_items([('id', 1), ('name', 'sample_name_0001')])

The class name is as above, but according to the Python 3.9.4 Documentation, the object returned by the above three methods is an object called a view object.

These objects can be specified in the [list] of the for statement.

The following is a simple program that uses keys() and values().

Source
sample_dict = {
    'id': 1,
    'name': 'sample_name_0001'
}

for key in sample_dict.keys():
    print(key)

print('----------------------------------')

for value in sample_dict.values():
    print(value)

It simply outputs the variables specified in the for statement. The execution result is as follows

Execution results
id
name
----------------------------------
1
sample_name_0001

Looking at the output results, we can see that the keys and values are stored in variables in each for statement.

To use the items() method in a for statement, write two variables as follows.

Source
sample_dict = {
    'id': 1,
    'name': 'sample_name_0001'
}

print('{0:>5}:{1:>20}'.format('key', 'value'))
for key, value in sample_dict.items():
    print('{0:>5}:{1:>20}'.format(key, value))
Execution results
  key:               value
   id:                   1
 name:    sample_name_0001

If you specify two variables separated by a comma in the for statement as shown above, the key and value will be stored in each.

I was not able to investigate the detailed grammar of why it is written this way. However, Python has an assignment called unpacking, and I think that rule is being applied.

In the following sample, the result of the items() method is made into a list type, and the first element is assigned to the variables key and value by unpacked assignment.

Source
sample_dict = {
    'id': 1,
    'name': 'sample_name_0001'
}

items_list = list(sample_dict.items())
print(f'{items_list=}')

print('----------------------------------')

item = items_list[0]
print(type(item))
print(f'{item=}')

print('----------------------------------')

key, value = item
print(f'{key=}, {value=}')
Execution results
items_list=[('id', 1), ('name', 'sample_name_0001')]
----------------------------------
<class 'tuple'>
item=('id', 1)
----------------------------------
key='id', value=1

The type() function used above will output the type name. The first element of the list is stored in the variable item, and the type name is output. The type name is output as tuple, which is simply a list that cannot be changed.

The left side of the last assignment expression describes the key and value, and the right side describes the tuple type. If you write it like this, it will store the values in order from left to right. The same thing seems to be applied in the for statement mentioned earlier.

Anyway, if you want to use dictionary type keys and values in a for statement, you should remember that you can write it as above.

That’s all. I hope this is helpful to you.

Articles next and previous in the same category