问题
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"
print od
Output:
defaultdict(<type 'dict'>, {'i': {'a': '111', 'b': '222'}})
Traceback (most recent call last):
File "app_main.py", line 51, in run_toplevel
File "/Users/adam/Desktop/collections.py", line 12, in <module>
od["i"]["a"] = "111"
KeyError: 'i'
Why the key error with OrderedDict and what I can do about it?
Thanks.
回答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.
回答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.
来源:https://stackoverflow.com/questions/15283578/ordereddict-keyerror