【发布时间】:2018-06-15 03:45:33
【问题描述】:
我正在为字典实现我的自定义迭代器,但我得到的只是键而不是项目。我的代码是:
initial_song_data = {
"blue-da-ba-dee-sample.ogg": {
"album": "Rush of Blood to the Head",
"path": "blue-da-ba-dee-sample.ogg",
"name": "blue da ba dee sample",
"artists": ["Coldplay", "Nirvana"]
},
"to-bring-you-my-love.ogg": {
"album": "Rush of Blood to the Head",
"path": "to-bring-you-my-love.ogg",
"name": "to bring you my love",
"artists": ["Nirvana", "U2"]
}}
iter_obj = iter(initial_song_data)
while True:
try:
element = next(iter_obj)
print(element.values())
except StopIteration:
break
for song in initial_song_data:
print(song)
输出: blue-da-ba-dee-sample.ogg
to-bring-you-my-love.ogg
我在这里缺少什么?请帮忙。
【问题讨论】:
-
您的代码在
while True:之后没有正确缩进请同时提供所需的输出。 -
完成了,现在可以检查了吗?
-
想要的输出?
-
目的是什么?在 Python 中,通常不需要这样做。
while循环很少使用。for循环可能更适合这种情况。
标签: python-3.x dictionary iterator