How to check if a key exists in a dictionary

anonymity
Release: 2020-09-17 15:31:41
Original
15887 people have browsed it

How to check whether a key exists in the dictionary: You can use the has_key() method to determine, such as [arr.has_key("int")]. A dictionary is a mutable container model, and it can also store objects of any type.

How to check if a key exists in a dictionary

Dictionary is another mutable container model and can store any type of object.

Each key-value (key=>value) pair in the dictionary is separated by a colon (:), each pair is separated by a comma (,), and the entire dictionary is included in curly braces ({}) , the format is as follows:

d = {key1 : value1, key2 : value2 }
Copy after login

Keys must be unique, but values ​​do not.

The value can be of any data type, but the key must be immutable, such as string, number or tuple.

The in method is used in python3

#判断字典中某个键是否存在
arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}
#使用 in 方法
if "int" in arr:
    print("存在")
if "float" in arr.keys():
    print("存在")
#判断键不存在
if "floats" not in arr:
    print("不存在")
if "floats" not in arr:
    print("不存在")
Copy after login

has_key() is not supported in python 3, but is supported in python2

#判断字典中某个键是否存在
arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}
#使用自带的has_key()
if(arr.has_key("int")):    
    print("存在")
Copy after login

The above is the detailed content of How to check if a key exists in a dictionary. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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