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.
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 }
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("不存在")
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("存在")
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!