2012-04-10 84 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