小编Mah*_*r I的帖子

在python中使用__getitem__迭代字典

我已经实现了一个 python 类来生成数据,如下所示:

class Array:
    def __init__(self):
        self.arr = [1,2,3,4,5,6,7,8]

    def __getitem__(self,key):
        return self.arr[key]

a = Array()
for i in a:
    print(i, end = " ")
Run Code Online (Sandbox Code Playgroud)

它按预期运行,我得到了关注

1 2 3 4 5 6 7 8
Run Code Online (Sandbox Code Playgroud)

但是,我想对字典做同样的事情。为什么我不能像这样迭代字典?

class Dictionary:
    def __init__(self):
        self.dictionary = {'a' : 1, 'b' : 2, 'c': 3}

    def __getitem__(self,key):
        return self.dictionary[key]
d = Dictionary()
for key in d:
    print(key, d[key], end=" ")
Run Code Online (Sandbox Code Playgroud)

我希望以下输出

a 1 b 2 c 3
Run Code Online (Sandbox Code Playgroud)

但是当我运行上面的代码时,出现以下错误:

Traceback (most recent call last):

  File "<ipython-input-33-4547779db7ec>", …
Run Code Online (Sandbox Code Playgroud)

python dictionary iterator python-3.x

8
推荐指数
2
解决办法
798
查看次数

标签 统计

dictionary ×1

iterator ×1

python ×1

python-3.x ×1