简体   繁体   中英

defaultdict key default value issues

I'm new to Python and having an issue with defaultdict. I have some json, where the lastInspection key isn't always present. I need to put a default value in for the date.

p.get("lastInspection", "") returns me {'date': '2018-01-03'}

problem = [{'lastInspection': {'date': '2018-01-03'}, 'contacts': []}]

for p in problem:
    print(p.get("lastInspection", ""))
    print(p.get("date", ""))

I am guessing, that the defaultdict is not what you want to use.

Default values should be declared in the second argument of the get method.

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM