這篇文章將為大家詳細(xì)講解有關(guān)Python中怎么互換字典的鍵值對(duì),文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
1.zip
dic = {'a':1, 'b':2, 'c':3} dic_new = dict(zip(dic.values(), dic.keys())) print(dic_new) # {1: 'a', 2: 'b', 3: 'c'}
2.循環(huán)
dic = {'a':1, 'b':2, 'c':3} dic_new = {} for key, val in dic.items(): dic_new[val] = key print(dic_new) # {1: 'a', 2: 'b', 3: 'c'}
3.列表生成器
dic_new = dict([val, key] for key, val in dic.items()) print(dic_new) # {1: 'a', 2: 'b', 3: 'c'}
關(guān)于Python中怎么互換字典的鍵值對(duì)就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。