2024-04-25 10:30:00 发布
网友
我有一个我正在创建的对象,有时它不会被创建,即None。你知道吗
None
我执行以下操作 dic.get("findThis")但由于dic有时是None,它将返回AttributeError: 'NoneType' object has no attribute 'get'
dic.get("findThis")
dic
AttributeError: 'NoneType' object has no attribute 'get'
有一些解决方案,比如使用
if not dic: print "MISSING" else: #do your stuff`.
有什么更好的办法?你知道吗
你在找三元运算符吗?你知道吗
result = dic.get("findThis") if dic else None
你可以用defaultdict这样使用它:
defaultdict
import collections #example function returning the dict def get_dict_from_json_response(): return {'findThis2':'FOUND!'} defdic = collections.defaultdict(lambda: 'MISSING') #get your dict dic = get_dict_from_json_response() if dic: defdic.update(dic) #copy values dic = defdic #now use defaultdict print [dic["findThis"],dic["findThis2"],dic["findThis3"],dic["findThis4"],dic["findThis5"],dic["findThis6"]]
输出:
['MISSING', 'FOUND!', 'MISSING', 'MISSING', 'MISSING', 'MISSING']
你在找三元运算符吗?你知道吗
result = dic.get("findThis") if dic else None
你可以用
defaultdict
这样使用它:输出:
相关问题 更多 >
编程相关推荐