在字典中枚举键?

16

我有一个字典

Dict = {'ALice':1, 'in':2, 'Wonderland':3}

我可以找到返回字典键值的方法,但是没有办法返回键名。

我希望Python逐步(通过for循环)返回字典键名,例如:

Alice
in
Wonderland

我可能会被诱惑将它转换为适当的值-键对列表,然后根据值进行排序,然后迭代。(请记住,字典中的键按顺序排列。) - user166390
排序对我来说不是问题。我不需要按特定顺序。我只是想将键名输入SQL数据库。 - upapilot
3个回答

22
你可以使用.keys()方法:
for key in your_dict.keys():
  print key
或者只需遍历该字典:
for key in your_dict:
  print 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

1
for key in your_dict.keys(): 可以简化为 for key in your_dict: - Nolen Royalty
@NolenRoyalty:谢谢!不知道我为什么会错过那个。 - Blender

2
def enumdict(listed):
    myDict = {}
    for i, x in enumerate(listed):
        myDict[x] = i

    return myDict

indexes = ['alpha', 'beta', 'zeta']

print enumdict(indexes)

打印结果:{'alpha': 0, 'beta': 1, 'zeta': 2}

编辑:如果你想使字典有序,请使用ordereddict。


虽然不是对问题的确切回答,但我点赞了,因为这是一个方便的技巧。 - port5432

1

字典有一个keys()方法。

Dict.keys()将返回一个键列表,或使用迭代器方法iterkeys()。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接