Python中检测dict中key是否存在的几种写法


1周前 11次点击 来自 其他

标签: Python

# 方式1:if - in
dict = {'a':1,'b':2,'c':3}
if 'a' in dic:
	...
if 'a' not in dic:
	...
	
# 方式2:keys()方法
if 'a' in dic.keys():
	...
if 'a' not in dic.keys():
	...

# 方式3: has_key()方法
if dic.has_key('a'):
	...

# 方式4:try-expect
try:
	value = dic['a']
expect:
	...

小结:不推荐使用try-expect , 首推Pythonic风格if-in

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1

Top ↑