upa*_*lot 11 dictionary python-2.7
我有一本字典
Dict = {'ALice':1, 'in':2, 'Wonderland':3}
Run Code Online (Sandbox Code Playgroud)
我可以找到返回键值的方法,但无法返回键名.
我希望Python逐步返回字典键名(for循环),例如:
Alice
in
Wonderland
Run Code Online (Sandbox Code Playgroud)
Ble*_*der 17
你可以使用.keys():
for key in your_dict.keys():
print key
Run Code Online (Sandbox Code Playgroud)
或者只是迭代字典:
for key in your_dict:
print key
Run Code Online (Sandbox Code Playgroud)
请注意,字典不是订购的.您生成的密钥将以稍微随机的顺序出现:
['Wonderland', 'ALice', 'in']
Run Code Online (Sandbox Code Playgroud)
如果你关心顺序,一个解决方案是使用清单,这是命令:
sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)]
for key, value in sort_of_dict:
print key
Run Code Online (Sandbox Code Playgroud)
现在你得到了你想要的结果:
>>> sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)]
>>>
>>> for key, value in sort_of_dict:
... print key
...
ALice
in
Wonderland
Run Code Online (Sandbox Code Playgroud)