2017-10-09 96 views
-11
province = {'ontario' : 'on', 'alberta' : 'ab', 'quebec' : 'qc', 'british_columbia' : 'bc'} 

capitals = { 'on' : 'toronto', 'ab': 'edmonton', 'qc' :'montreal', 'bc': 'victoria'} 

並且我像輸出一樣;將第一個字典鍵與第二個字典值結合起來

' the capital of Ontario is toronto' 
' the capital of alberta is edmonton' 

回答

1

您應該爲您的問題提供更多細節,使其更清晰。根據你的問題,我知道你想把第一個字典的鍵值映射到第二個字符的值。

,假設第二dict有第一作爲鍵,你可以使用下面的代碼片段的值:

province = {'ontario' : 'on', 'alberta' : 'ab', 'quebec' : 'qc', 'british_columbia' : 'bc'} 
capitals = { 'on' : 'toronto', 'ab': 'edmonton', 'qc' :'montreal', 'bc': 'victoria'} 
result = dict() 
for key, value in province.items(): 
    result[key] = capitals[value] 

#>>> result 
#{'ontario': 'toronto', 'british_columbia': 'victoria', 'quebec': 'montreal', 'alberta': 'edmonton'} 
1

只是一個循環:

for key, value in province.items(): province[key] = capitals[value] 

希望這是你想要的。

+0

是否\t的\t代碼\t做\t什麼\t是\t問\t爲\t和\t工作\t爲\t任意\t尺寸\t要麼\t字典\t? – ram

相關問題