作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一本字典
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/
我是一名优秀的程序员,十分优秀!