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

How to find elements in a dictionary in Python

王林
Release: 2023-05-15 20:10:09
forward
1465 people have browsed it

Context code

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

The first way: []

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

smart_girl["name"]   #[]传入key
Copy after login

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
Copy after login

or

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

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
Copy after login

Or

smart_girl.setdefault("name","无名氏")
Copy after login

or

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

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template