gpt4 book ai didi

dictionary - 枚举字典中的键?

转载 作者:行者123 更新时间:2023-12-03 00:42:48 34 4
gpt4 key购买 nike

我有一本字典

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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com