因此,我必須編寫一個函數,它接收一個字典作爲輸入參數,並返回輸入字典的反向,其中原始字典的值用作返回字典的鍵,原始字典的鍵是用作返回字典的值。反向字典。輸出保持變化
例如,如果該功能被稱爲
reverse_dictionary({'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'astute': ['Smart', 'clever'], 'smart': ['clever', 'bright', 'talented']})
然後我的函數返回
{'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'talented': ['smart'], 'bright': ['smart'], 'exact': ['accurate'], 'smart': ['astute']}
這裏是我的功能
def reverse_dictionary(input_dict):
d={}
def countEmpty(dictionario):
count=0
for k,v in dictionario.items():
if(len(dictionario[k])==0):
count+=1
return count
def removo(dicto, dicto2):
for k,v in dicto.items():
#v.sort()
if (len(dicto[k])!=0):
if v[-1] not in dicto2:
dicto2[v[-1].lower()]=[k.lower()]
else:
dicto2[v[-1]].append(k.lower())
dicto[k]=v[:-1]
while countEmpty(input_dict)<len(input_dict):
removo(input_dict,d)
for k,v in d.items():
v.sort()
return d
dicta={'astute': ['Smart', 'clever', 'talented'], 'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'talented': ['smart', 'keen', 'Bright'], 'smart': ['clever', 'bright', 'talented']}
print(reverse_dictionary(dicta))
程序開始工作。它反轉字典。但字典中的值需要排序。 我測試過該程序具有:
dicta={'astute': ['Smart', 'clever', 'talented'], 'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'talented': ['smart', 'keen', 'Bright'], 'smart': ['clever', 'bright', 'talented']}
它有時會返回:
{'keen': ['talented'], 'talented': ['astute', 'smart'], 'clever': ['astute', 'smart'], 'exact': ['accurate'], 'bright': ['smart', 'talented'], 'precise': ['accurate', 'exact'], 'smart': ['astute', 'talented']}
哪個是正確答案,但有時它也返回:
{'bright': ['smart', 'talented'], 'exact': ['accurate'], 'talented': ['astute', 'smart'], 'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'smart': ['astute'], 'keen': ['talented']}
其中有'聰明'鍵缺少'天賦'的價值。即使我沒有做任何改變代碼。我知道Python中的字典並沒有任何順序,但不應該保持一致?爲什麼會發生?
詞典是由設計無序的。另外,決定用「精確」來做什麼決不是不可能的:['準確','確切']? 「準確」還是「準確」成爲關鍵? – jDo
你正在修改你的字典,而迭代它...不是一個明智的想法 – Idos
@jDo他們都將成爲鍵精確作爲他們兩個的價值 – slau