SoFunction
Updated on 2024-12-20

python3 access to values in a dictionary example method

Nowadays, dictionary is also a hot topic when we learn python, many people say, as long as you master the dictionary, it is equivalent to mastering half of python, in fact, why do people say so? Usually, when we use dictionaries, we always encounter the trilogy in programming data, writing, accessing, using, and among them, accessing is also considered to be a more important content, let's take a look at it together~.

access value

We access the values in a list by providing an index. Similarly, in a dictionary, values are accessed by using keys.

grades['John']
'A'

('Betty')
'B'

Access to all values or all keys

The keys method is used to get all the keys.

()
dict_keys(['John', 'Emily', 'Betty', 'Mike', 'Ashley'])

The return object is a dict_keys object, which is of type iterable. Therefore, we can iterate over it in a for loop.

Similarly, the values method returns all values.

()
dict_values(['A', 'A+', 'B', 'C', 'A'])

We can't do indexing operations on dict_keys or dict_values, but we can convert them to a list and then use the index.

list(())[0]
'A'

The items method returns key-value pairs.

()
dict_items([('John', 'A'), ('Emily', 'A+'), ('Betty', 'B'), ('Mike', 'C'), ('Ashley', 'A')])

python access to dictionary content extensions:

Accessed via key-value pairs:

print(dict[key])

dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
print(dict['D'])

exports:
ee

(key,[default]): default is optional, it is used to return a default value when the 'key' does not exist, if omitted, the default value will be None.

dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
print((2))
print((3))
print((4, ['No element with key 4 exists in the dictionary']))

exports:
aa
None
['No element with key 4 exists in the dictionary']

to this article on the python3 access to the value of the dictionary example method is introduced to this article, more related python3 how to access the value of the dictionary content, please search my previous posts or continue to browse the following related articles I hope you will support me in the future more!