我如何在python中使用默认的有序dict

时间:2013-04-26 03:33:09

标签: python dictionary

我正在关注这个例子 Can I do an ordered, default dict in Python?

但是当我使用这个

if mydict['item']`

然后我收到了关键错误。它不应该给我这个错误。

即使密钥不存在,也不应该是空的

1 个答案:

答案 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'
相关问题