【发布时间】:2017-08-22 03:03:51
【问题描述】:
我有大量数据,在循环中迭代 true this 并按键附加值:
for q in my_dict:
output.append({"roomsCount": q['roomsCount'], "totalArea": float(q['totalArea']),
"floorNumber": q['floorNumber'],"price": int(q['bargainTerms']['price']), ...})
有时我得到:KeyError: 'roomsCount' 或 KeyError: 'totalArea' 等,如果密钥不存在。
如果该键不存在,我如何为任何键设置默认值?无需重复尝试:除了我的每个键:值对
【问题讨论】:
-
见
dict.get和dict.setdefault -
这可能与您的错误无关,但您的
my_dict变量似乎被误导了。如果你遍历一个字典,你会得到键。看起来my_dict是一个字典列表(或某种类似的可迭代对象)。 -
谢谢,问题已解决
标签: python python-3.x dictionary exception keyerror