在 Python 中,您可以迭代字典的键、值和 (key, value) 对,如下所示...
for key in test.keys():
print('key : ', key)
print()
for value in test.values():
print('value : ', value)
print()
for item in test.items():
print('item : ', item)
输出...
key : Default
key : Test
key : Master
value : {'test_data': {'data': 'test'}}
value : {'abc_data': {'data': 'test'}}
value : {'zxy_data': {'data': 'test'}}
item : ('Default', {'test_data': {'data': 'test'}})
item : ('Test', {'abc_data': {'data': 'test'}})
item : ('Master', {'zxy_data': {'data': 'test'}})
现在让我们来看看你的代码,看看发生了什么......
下面的代码将打印密钥。即变量“item”将包含字符串格式的键。
for item in test:
print(item)
输出...
Default
Test
Master
您已经使用函数 iter() 函数创建了密钥字符串,并尝试使用 next() 函数迭代密钥字符串的字符。但是下面给出了迭代字符串的正确方法...
s = iter('abcd')
while True:
try:
item = next(s)
print(item)
except StopIteration as exception:
break
输出...
a
b
c
d
由于您没有在任何循环中使用 next() 函数,它只打印键的第一个字符。在下一次迭代中,选择了下一个键,因此它打印了第二个键的第一个字母,依此类推。
现在让我们修改您的代码,以便您可以得到预期的结果...
for item in test:
key = iter(item)
key_string = ''
while True:
try:
character = next(key)
key_string += character
except StopIteration as exception:
break
print('Key : ', key_string)
输出...
Key : Default
Key : Test
Key : Master
您可以尝试制作自己的迭代器来理解 StopIteration 异常。