加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 与dict.fromkeys()和类似dict的对象的KeyError

发布时间:2020-12-20 11:11:55 所属栏目:Python 来源:网络整理
导读:在 Python中,您可以使用字典作为dict.fromkeys()的第一个参数,例如: In [1]: d = {'a': 1,'b': 2}In [2]: dict.fromkeys(d)Out[2]: {'a': None,'b': None} 我尝试用类似dict的对象做同样的事情,但这总是引发一个KeyError,例如: In [1]: class SemiDict: ..
在 Python中,您可以使用字典作为dict.fromkeys()的第一个参数,例如:

In [1]: d = {'a': 1,'b': 2}

In [2]: dict.fromkeys(d)
Out[2]: {'a': None,'b': None}

我尝试用类似dict的对象做同样的事情,但这总是引发一个KeyError,例如:

In [1]: class SemiDict:
   ...:     def __init__(self):
   ...:         self.d = {}
   ...:
   ...:     def __getitem__(self,key):
   ...:         return self.d[key]
   ...:
   ...:     def __setitem__(self,key,value):
   ...:         self.d[key] = value
   ...:
   ...:

In [2]: sd = SemiDict()

In [3]: sd['a'] = 1

In [4]: dict.fromkeys(sd)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)

C:binConsole2&;ipython console> in <module>()

C:binConsole2&;ipython console> in __getitem__(self,key)

KeyError: 0

到底发生了什么?除了使用像dict.fromkeys(sd.d)这样的东西之外,还能解决吗?

解决方法

要创建dict,fromkeys会遍历其参数.所以它必须是一个迭代器.使其工作的一种方法是在你的dict中添加一个__iter__方法:

def __iter__(self):
    return iter(self.d)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读