[英]defaultdict key default value issues
我是 Python 新手,並且在使用 defaultdict 時遇到了問題。 我有一些 json,其中 lastInspection 鍵並不總是存在。 我需要為日期輸入一個默認值。
p.get("lastInspection", "")
返回我{'date': '2018-01-03'}
problem = [{'lastInspection': {'date': '2018-01-03'}, 'contacts': []}]
for p in problem:
print(p.get("lastInspection", ""))
print(p.get("date", ""))
我猜, defaultdict 不是你想要使用的。
默認值應該在get
方法的第二個參數中聲明。
problem = [{'lastInspection': {'date': '2018-01-03'}, 'contacts': []}]
default_inspection = { 'date': '2018-01-03' }
for p in problem:
# default_inspection is returned, when 'lastInspection' is not present in the json
inspection = p.get("lastInspection", default_inspection)
print(inspection)
# now you access date, as you are sure, that it is present
print(inspection['date'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.