我有字典
Dict = {'ALice':1, 'in':2, 'Wonderland':3}
我可以找到返回键值的方法,但无法返回键名。
我希望 Python 逐步返回字典键名(for 循环),例如:
Alice
in
Wonderland
最佳答案
您可以使用 .keys()
:
for key in your_dict.keys():
print key
或者只是遍历字典:
for key in your_dict:
print key
请注意,字典不是有序的。您生成的 key 将以某种随机的顺序出现:
['Wonderland', 'ALice', 'in']
如果您关心订单,解决方案是使用有序的列表:
sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)]
for key, value in sort_of_dict:
print key
现在你得到了你想要的结果:
>>> sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)]
>>>
>>> for key, value in sort_of_dict:
... print key
...
ALice
in
Wonderland
关于dictionary - 枚举字典中的键?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10083580/