2012-04-10 83 views
7

我有一本字典枚举字典中的键?

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

我会想办法返回键的值,但是没有办法返回键名。

我想要的Python返回字典的键名循序渐进(for循环)例如:

Alice 
in 
Wonderland 
+0

我可能会试图将其转换为适当的值键对列表,然后根据此示例中的值进行排序,然后进行迭代。 (请记住,字典中的键不是*排序的。) – 2012-04-10 05:36:30

+0

排序对我来说不是问题。我不需要按特定的顺序。我只是试图将键名输入到SQL数据库中。 – upapilot 2012-04-10 05:40:27

回答

13

您可以使用.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 
+0

是的,我正在编辑它。谢谢! – Blender 2012-04-10 05:37:48

+1

'对于your_dict.keys()中的键:'可以简化为'for your_dict中的键:' – 2012-04-10 05:38:55

+0

好吧,非常感谢。订购对我来说不是问题:) – upapilot 2012-04-10 05:38:57

1

dict有一个keys()方法。

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

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

    return myDict 

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

print enumdict(indexes) 

打印:{ '阿尔法':0, '测试版':1, '泽塔':2}

编辑:如果你想在字典被下令使用ordereddict。

+0

不完全是问题的答案,但我赞成,因为它是方便的技巧。 – ardochhigh 2014-07-18 08:46:58