[英]defaultdict key default value issues
I'm new to Python and having an issue with defaultdict.我是 Python 新手,并且在使用 defaultdict 时遇到了问题。 I have some json, where the lastInspection key isn't always present.我有一些 json,其中 lastInspection 键并不总是存在。 I need to put a default value in for the date.我需要为日期输入一个默认值。
p.get("lastInspection", "")
returns me {'date': '2018-01-03'}
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", ""))
I am guessing, that the defaultdict is not what you want to use.我猜, defaultdict 不是你想要使用的。
Default values should be declared in the second argument of the get
method.默认值应该在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.