Get the App
SLTechnology News&Howtos  ›  Development  › 

How does python get the dictionary entry with the get () method

Shulou Source: shulou.com Published: 2022-06-01 04:52:01 10月24日 Update

This article mainly shows you how python uses the get() method to obtain dictionary items. The content is simple and easy to understand. It is clearly organized. I hope it can help you solve your doubts. Let Xiaobian lead you to study and learn this article "how python uses the get() method to obtain dictionary items."

Stop using square brackets to get dictionary entries and replace them with.get()

For example, there is the following dictionary:

person = {'name': 'John', 'age': 20}

We can get name and age from person[name] and person[age] respectively. However, for some reason we want to get a key that doesn't exist, such as "salary," and running person[salary] raises a KeyError.

The get() method is useful. If the key is in the dictionary, the get() method returns the value of the specified key, but Python returns None if the key is not found. Thanks to this, your code will not break.

person = {'name': 'John', 'age': 20}print('Name: ', person.get('name'))print('Age: ', person.get('age'))print('Salary: ', person.get('salary'))

The output is as follows:

Name: John

Age: 20

Salary: None

The above is all the content of this article "Python how to use the get() method to obtain dictionary items", thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!

Tags: Dictionary method content article study help code reason can be passed name salary age square brackets easy to understand more useful organized knowledge results tape Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Docker MySQL Xiaomi Microsoft