2012-10-26 144 views
0
states = {state, abbr} 
cities = {abbr, capital} 

我想打印出state, abbr, capital或其他3個值的其他順序。 我試圖反轉的關鍵,在州值對:從兩本字典打印

inv_states = {state: abbr for abbr, state in states.items()} 
for abbr, capital in sorted(inv_states.items()): 
     print(abbr, ':', capital) 

現在,我已經有了:

states = {abbr, state} 
cities = {abbr, capital} 

然後試圖創建一個新的字典(我不完全理解下面的代碼):

newDict = defaultdict(dict) 
for abbr in (inv_states, cities): 
     for elem in abbr: 
       newDict[elem['index']].update(elem) 
fullDict = newDict.values() 
print(fullDict) 

但我得到一個string indices must be intergers錯誤。

請幫忙。還是我完全走錯了路?謝謝。

+0

我在這裏有點困惑。你想做什麼? – Blender

+3

'{state,abbr}',這是一個集合,而不是字典。 –

+0

請在保存編輯之前查看問題的外觀。 – Blender

回答

3

假設您的數據是字典(不在您的示例代碼中)。它應該是相當簡單的產生你正在尋找的數據

for state, abbr in states.items(): 
    print('{0}, {1}, {2}'.format(state, abbr, cities[abbr])) 
+1

這不適用於Python 3.1(因爲問題標題要求); 'print'應該是一個函數。 –