Home >Backend Development >Python Tutorial >How to find elements in a dictionary in Python

How to find elements in a dictionary in Python

王林
王林forward
2023-05-15 20:10:091463browse

Context code

smart_girl = {"name":"yuan wai", "age": 25,"sex":"女"}

The first way: []

Note: In this way, if the corresponding key cannot be found , a KeyError will be reported

smart_girl["name"]   #[]传入key

Second method: get method

Note: The get method will not raise KeyError and will return a default value

smart_girl.get("name") #注意:key未指定返回的默认值,找不到对应的key,会返回None

or

smart_girl.get("sex", "找不见性别") #可以指定key不存在时,返回一个指定的默认值

The third way: setdefault method

Note: The setdefualt method will not cause KeyError, the same as the get method

smart_girl.setdefault("name") #未指定默认值,找不到key,会返回None

Or

smart_girl.setdefault("name","无名氏")

or

smart_girl.setdefault("name",default="无名氏") #指定返回默认值,找不到key时,返回默认值

The above is the detailed content of How to find elements in a dictionary in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete