OrderedDict KeyError

好久不见. 提交于 2019-12-24 10:57:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!