您将创建15个独立的迭代器,每个迭代器从头开始。试着只创建一个迭代器,然后只调用next。在My_dict = {'What is your name?':'Emma','What is your age':34,'What color eyes do you have':'Blue'}
x = iter(My_dict.keys())
for i in range(3):
print(next (x))
结果:
^{pr2}$
不过,请注意,“你叫什么名字?”没有首先打印,尽管它是字典文本中出现在代码第一行的第一个键。这是因为字典是无序的;当迭代字典的键/值时,Python可以自由地按它喜欢的顺序生成条目。如果需要按特定顺序打印问题,请考虑使用collections.OrderedDict。在import collections
My_dict = collections.OrderedDict((('What is your name?','Emma'),('What is your age',34),('What color eyes do you have','Blue')))
x = iter(My_dict.keys())
for i in range(3):
print(next (x))
结果:What is your name?
What is your age
What color eyes do you have
或者,如果你不需要在给定问题内容的情况下对答案进行固定时间的访问,那么最好不要使用词典:my_tuple = (('What is your name?','Emma'),('What is your age',34),('What color eyes do you have','Blue'))
for i in range(3):
print my_tuple[i][0]