描述:
讀入一個字典類型的字符串,反轉其中鍵值對輸出。
即,讀入字典key:value模式,輸出value:key模式。
輸入格式
用戶輸入的字典格式的字符串,如果輸入不正確,提示:輸入錯誤。
輸出格式
給定字典d,按照print(d)方式輸出
方法一:
turn_dic=input()
n={}
try:
dic=eval(turn_dic)
for key,value in dic.items():
n.update({value:key})
print(n)
except:
print("輸入錯誤")
知識點描述
1、Python 字典(Dictionary) items() 函數以列表返回可遍歷的(鍵, 值) 元組數組。語法:dict.items()返回值:返回可遍歷的(鍵, 值) 元組數組。
2、Python 字典(Dictionary) update(dict2) 函數把字典dict2的鍵/值對更新到dict里
方法二
dict=eval(input()) #輸入格式:dict = {"a":1,"b":2}
dict_new={}
try:
for k,v in dict.items():
dict_new[v]=k #鍵值互換
print(dict_new)
except:
print("輸入錯誤")
方法三
turn_dic=input()
n={}
try:
dic=eval(turn_dic)
n=dict([(value,key) for key,value in dic.items()])
print(n)
except:
print("輸入錯誤")
知識點描述
使用列表推導式
方法四
def reC(myDict): # 對字典反轉的第二種方法,使用壓縮器
new_dict = dict(zip(myDict.values(), myDict.keys()))
return new_dict
知識點描述
使用壓縮器。
python字典反轉的兩種方法
真是方法多到驚訝!