OrderedDict KeyError
import collections d = collections.defaultdict(dict) d['i']['a'] = '111' d['i']['b'] = '222' print d od = collections.OrderedDict() od['i']['a'] = '111' od['i']['b'] = '222'
Solution 1:
An OrderedDict
is not also a defaultdict
. You'd have to do something like this:
import collections
od = collections.OrderedDict()
od["i"] = collections.OrderedDict()
od["i"]["a"] = "111"
od["i"]["b"] = "222"
print od
Output:
OrderedDict([('i', OrderedDict([('a', '111'), ('b', '222')]))])
See this answer for a potential ordered defaultdict implementation.
Solution 2:
Thats the main advantage of defaultdict especially, it will capture the Keyerror and call the function passed as the argument to defaultdict. But OrderedDict is for different purpose.
If a new dataStrcture combines both functionality would be beneficial. Also, using userDict() it must be possible to implement such a functionality.
You can refer my article on Python Collections
https://techietweak.wordpress.com/2015/11/11/python-collections/
Hope this helps.
Post a Comment for "OrderedDict KeyError"