我正在关注这个例子 Can I do an ordered, default dict in Python?
但是当我使用这个
时if mydict['item']`
然后我收到了关键错误。它不应该给我这个错误。
即使密钥不存在,也不应该是空的
答案 0 :(得分:2)
要在dict中使用默认值,必须设置default_factory,它必须是可调用的。
使用示例:
d = DefaultOrderedDict(lambda: None)
assert d['item'] is None
# as with normal dict, you can init it with another dict
d = {'key': 'value'}
d = DefaultOrderedDict(list, d)
assert d['item'] == []
assert d['key'] == 'value'