本文介绍了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"

print od

输出:

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'

为什么OrderedDict出现关键错误,我该怎么办?

Why the key error with OrderedDict and what I can do about it?

谢谢.

推荐答案

OrderedDict也不是defaultdict.您必须执行以下操作:

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

输出:

OrderedDict([('i', OrderedDict([('a', '111'), ('b', '222')]))])

请参见此答案以了解可能的命令defaultdict实现.

See this answer for a potential ordered defaultdict implementation.

这篇关于OrderedDict KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 08:46