[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
<>前言
今天写代码遇到一个问题,如果要获取字典中某个key的value,那么很简单,直接获取就行了。
但是如果不确定这个字典中是否存在这个key,那直接获取就有可能会报错,那么会有一个KeyError
的错误被抛出,当然你也可以直接通过捕获异常的方式来处理这个问题,但我更推荐大家提前判断这个字典中是否有这个key,也就是提前预断错误是否会发生,并且及时的避免它。
<>判断方法
*
第一种方法:使用has_key()方法
# 生成一个字典 dict = {'name': '','age': '','sex': ''} # 打印返回值 print(dict.has_key(
'name')) # 结果返回True print(dict.has_key('id')) # 结果返回False
不过这个方法在新版的Python中貌似已经被移除了,那么大家也可以使用第二种方法。
*
第二种方法:使用keys()方法
# 生成一个字典 dict = {'name': '','age': '','sex': ''} #
判断是否存在,其中dict.keys()是列出字典所有的key print('name' in dict.keys()) # 结果返回True print(
'id' in dict.keys()) # 结果返回False
除了使用in也可以使用not in,用于判定这个key不存在
*
第三种方法:优雅的使用 in 关键字(Python3支持,Python2不清楚)
# 生成一个字典 dict = {'name': '','age': '','sex': ''} # 判断key是否存在于dict中 print('name'
in dict) # 结果返回True print('id' in dict) # 结果返回False
这也是我个人比较推荐的一种用法
<>结语
欢迎大家点赞转发,如果文章中有讲的不对的地方,也欢迎大家在评论区进行指正,谢谢!