Python defaultdict键默认值问题

Python defaultdict键默认值问题,python,json,defaultdict,Python,Json,Defaultdict,我是Python新手,对defaultdict有意见。 我有一些json,其中lastInspection键并不总是存在。我需要为日期输入一个默认值 p.get(“上次检查”)返回我{'date':'2018-01-03'} problem = [{'lastInspection': {'date': '2018-01-03'}, 'contacts': []}] for p in problem: print(p.get("lastInspection", "")) prin

我是Python新手,对defaultdict有意见。 我有一些json,其中lastInspection键并不总是存在。我需要为日期输入一个默认值

p.get(“上次检查”)
返回我
{'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'])

现在还不清楚您想问我们什么问题,或者defaultdict应该如何参与。非常感谢Marek Wawrzos,这非常有效!不会想到使用默认值。