2014-04-16 107 views
4

我的色彩搭配多個值的字典:Python字典多值

dictcolors = {'Red': '1,2,3,4,5', 
       'Green': '3,4,5', 
       'Purple': '6', 
       'Orange': '7', 
       'Blue': '1,2,3', 
       'Teal': '3,4,5,6'} 

你怎麼能在所有值進行迭代,並返回值和鍵(S),該​​值的一部分嗎?

Result: 
Value - Key(s) 

1 - 'Red', 'Blue' 
2 - 'Red', 'Blue' 
3 - 'Red', 'Green', 'Blue', 'Teal' 
4 - 'Red', 'Green', 'Teal' 
5 - 'Red', 'Green', 'Teal' 
6 - 'Purple', 'Teal' 
7 - 'Orange' 
+4

哪裏是你的代碼,到目前爲止,恰恰什麼是它的問題? – jonrsharpe

+0

看起來你正在使用錯誤的數據類型。使用字典從價值中查找關鍵字就像買飛機,所以你可以每天打車去打工。它速度慢,效率低,笨重,而且在曲面街道上看起來很荒謬。 –

回答

7

可以爲此使用defaultdict(可從PY 2.6+):

from collections import defaultdict 
foundColors = defaultdict(set) 
for key,value in dictcolors.iteritems(): 
    # Assuming the numbers are in a comma separated string 
    for color in value.split(','): 
     foundColors[color].add(key) 

foundColors給出:

>>defaultdict(<type 'set'>, {'1': set(['Blue', 'Red']), '3': set(['Blue', 'Green', 'Red', 'Teal']), '2': set(['Blue', 'Red']), '5': set(['Green', 'Red', 'Teal']), '4': set(['Green', 'Red', 'Teal']), '7': set(['Orange']), '6': set(['Purple', 'Teal'])}) 

使用defaultdict的另一個優點是它不會休息的時候訪問dictcolors中不存在的號碼。這是因爲當你訪問這樣的密鑰時,它將通過一個空的「默認」類型(在這種情況下是set)來初始化密鑰的值。

所以,你可以做這樣的事情不會有問題:

for number in range(10): 
    print number,list(foundColors[number]) 
-1

嘗試是這樣的:

integer count = 0; 
for key in dictcolors.keys():{ 
    print '{0}'.format(str(count)) + ' - ' 
    if (dictcolors[key].find(str(count))) 
     print key 
+0

你確定這是python嗎? –

+0

對不起,我只是一個初學者在stackoverflow,我沒有Python的GUI。這就是爲什麼我把這個例子作爲一個想法。 –

+0

沒關係。但爲了將來的參考,你可能想運行你的代碼來檢查它是否正確。用python它確實很容易做到。 :) –