SoFunction
Updated on 2024-11-15

python determine whether a list dictionary string tuple exists a certain value or null value (multiple methods)

Determine if a value exists

The almighty in vs. not in:
In strings, lists, tuples, and dictionaries, you can use in and not in to determine whether a value exists.
String:

>>> a='baidu'
>>> 'ba' in a
True
>>> 'ab' in a
False

List:

>>> b=['baidu','taobao','jingdong',3]
>>> 3 in b
True
>>> 'taobar' in b
False

Tuple:

>>> c=('taobao','jingdong')
>>> 'taobao' in c
True
>>> 'tatao' in c
False

Dictionary:
If you don't add keys or values, just compare key

>>> d={'taobao':12,'jingdong':23}
>>> 'taobao' in d
True
>>> 12 in d
False
>>> 12 in ()
False
>>> 12 in ()
True

In python2 you can also use the has_key method

>>> d.has_key('taobao')
True
>>> d.has_key('taob3')
False

Determine if the value is null

Method I:
In Python, False,0,'',[],{},() are all false, so you can perform logical operations directly. It is recommended to use this method for better performance.
For example:

a=[]
if a:
	print 22
else:
	print 33
> if d['jingdong']:
...     print 22
...
22

Method II:
You can use the function len() to compare.

>>> len(a)
0
>>> a=''
>>> b=[]
>>> len(a)
0
>>> len(b)
0
>>> e={}
>>> len(e)
0

to this article on the python judgment list dictionary string tuple whether there is a value or null value of the article is introduced to this, more related python judgment list dictionary string tuple content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!