Python在dictionary update方法中使用iterable对象

Python的dictionary是个很常用的数据类型。可以使用update方法来对里面的key/pair进行赋值和更新。对于update方法的参数,除了使用另外一个dictionary对象之外,还能使用任意的iterable的对象,比如list。

这里我尝试使用一个自定义的iterable对象,作为update的参数。

class MyIterableClass:
def __init__(self):
return
def __iter__(self):
self.x = 1
return self
def __next__(self):
if self.x > 10:
raise StopIteration()
else:
result = self.x
self.x += 1
return (result, result)

a = MyIterableClass()
t = {}
t.update(a)
print(t)

程序运行输出:

(py37) PS C:\\tmp> python .\\dict_update.py
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}
(py37) PS C:\\tmp>

可以看到iterable对象的每个key/value对,都被付给了dictionary对象。


分享到:


相關文章: