Python中實現(xiàn)兩個字典(dict)合并的方法
更新時間:2014年09月23日 15:34:28 投稿:shichen2014
這篇文章主要介紹了Python中實現(xiàn)兩個字典(dict)合并的方法,是Python程序設(shè)計中非常實用的技巧,需要的朋友可以參考下
本文實例講述了Python中實現(xiàn)兩個字典(dict)合并的方法,分享給大家供大家參考。具體方法如下:
現(xiàn)有兩個字典dict如下:
dict1={1:[1,11,111],2:[2,22,222]}
dict2={3:[3,33,333],4:[4,44,444]}
合并兩個字典得到類似:
{1:[1,11,111],2:[2,22,222],3:[3,33,333],4:[4,44,444]}
方法1:
dictMerged1=dict(dict1.items()+dict2.items())
方法2:
dictMerged2=dict(dict1, **dict2)
方法2等同于:
dictMerged=dict1.copy() dictMerged.update(dict2)
或者:
dictMerged=dict(dict1) dictMerged.update(dict2)
方法2比方法1速度快很多,用timeit測試如下
$ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged1=dict(dict1.items()+dict2.items())' 10000 loops, best of 3: 20.7 usec per loop $ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged2=dict(dict1,**dict2)' 100000 loops, best of 3: 6.94 usec per loop $ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged3=dict(dict1)' 'dictMerged3.update(dict2)' 100000 loops, best of 3: 7.09 usec per loop $ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged4=dict1.copy()' 'dictMerged4.update(dict2)' 100000 loops, best of 3: 6.73 usec per loop
希望本文所述對大家的Python程序設(shè)計有所幫助。
相關(guān)文章
Python腳本實現(xiàn)Mysql數(shù)據(jù)遷移
MySQL數(shù)據(jù)庫遷移是指將MySQL數(shù)據(jù)庫中的數(shù)據(jù)和結(jié)構(gòu)遷移到另一個MySQL實例,下面小編就來為大家介紹一下如何通過Python腳本實現(xiàn)Mysql數(shù)據(jù)遷移吧2025-03-03
用django設(shè)置session過期時間的方法解析
這篇文章主要介紹了用django設(shè)置session過期時間的方法解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08
pytorch教程網(wǎng)絡(luò)和損失函數(shù)的可視化代碼示例
這篇文章主要介紹了pytorch教程中網(wǎng)絡(luò)和損失函數(shù)的可視化,文中附含詳細的代碼示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-09-09
torch 中各種圖像格式轉(zhuǎn)換的實現(xiàn)方法
這篇文章主要介紹了torch 中各種圖像格式轉(zhuǎn)換的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12

