-1

I am following this example Can I do an ordered, default dict in Python?

But when i use this

if mydict['item']`

then i am getting the key error. It should not give me that error.

Shouldn't it suppose to be empty even if key don't exist

Community
  • 1
  • 1
user2294401
  • 377
  • 2
  • 6
  • 14

1 Answers1

2

To have default values in your dict, you have to set default_factory, which must be a callable.

Example usage:

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'
gatto
  • 2,947
  • 1
  • 21
  • 24