字典是Python語言中唯一的映射類型,在我們日常工作中經常會遇到,下面這篇文章主要給大家介紹了關於Python中如何優雅的合併兩個字典(dict)的相關資料,文中透過範例程式碼介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。
前言
字典是Python中最強大的資料類型之一,本文將給大家詳細介紹關於Python合併兩個字典(dict)的相關內容,分享出來供大家參考學習,話不多說了,來一起看看詳細的介紹吧。
一行程式碼合併兩個dict
#假設有兩個dict x和y,合併成一個新的dict,不改變x和y的值,例如
x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4}
期望得到一個新的結果Z,如果key相同,則y覆寫x。期望的結果是
>>> z {'a': 1, 'b': 3, 'c': 4}
在PEP448中,有一個新的語法可以實現,並且在python3.5中支援了該語法,合併程式碼如下
z = {**x, **y}
妥妥的一行程式碼。 由於現在很多人還在用python2,對於python2和python3.0-python3.4的人來說,有一個比較優雅的方法,但是需要兩行程式碼。
z = x.copy() z.update(y)
上面的方法,y都會覆寫x裡的內容,所以最終結果b=3.
不使用python3 .5如何一行完成了
如果您還沒有使用Python 3.5,或者需要編寫向後相容的程式碼,並且您希望在單一表達式中運行,則最有效的方法是將其放在一個函數中:
def merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z
然後一行程式碼完成呼叫:
z = merge_two_dicts(x, y)
你也可以定義一個函數,合併多個dict,例如
##
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result然後可以這樣使用
z = merge_dicts(a, b, c, d, e, f, g)所有這些裡面,相同的key,都是後面的覆蓋前面的。
一些不夠優雅的示範
#items
z = dict(x.items() + y.items())這其實就是在記憶體中建立兩個列表,再建立第三個列表,拷貝完成後,建立新的dict,刪除掉前三個列表。這個方法耗費效能,而且對於python3,這個無法成功執行,因為items()回傳是個物件。
>>> c = dict(a.items() + b.items()) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'你必須明確的把它強制轉換成list,
z = dict(list(x.items()) + list(y.items() )) ,這太浪費效能了。 另外,想以來於
items()返回的list做並集的方法對於python3來說也會失敗,而且,並集的方法,導致了重複的key在取值時的不確定,所以,如果你對兩個dict合併有優先順序的要求,這個方法就徹底不合適了。
>>> x = {'a': []} >>> y = {'b': []} >>> dict(x.items() | y.items()) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'這裡有一個例子,其中y應該有優先權,但由於任意的集合順序,x的值被保留:
>>> x = {'a': 2} >>> y = {'a': 1} >>> dict(x.items() | y.items()) {'a': 2}
建構子
z = dict(x, **y)這樣用很好,比前面的兩步驟的方法高效多了,但是可閱讀性差,不夠pythonic,如果當key不是字串的時候,python3中還是運行失敗
>>> c = dict(a, **b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: keyword arguments must be stringsGuido van Rossum 大神說了:宣告
dict({}, {1:3})是非法的,因為畢竟是濫用機制。雖然這個方法比較hacker,但太投機取巧了。
一些性能較差但是比較優雅的方法
{k: v for d in dicts for k, v in d.items()}python2.6中可以這樣
dict((k, v) for d in dicts for k, v in d.items())itertools.chain 將以正確的順序將鍵值對上的迭代器連結:
import itertools z = dict(itertools.chain(x.iteritems(), y.iteritems()))
「效能測試
#
>>> min(timeit.repeat(lambda: merge_two_dicts(x, y))) 0.5726828575134277 >>> min(timeit.repeat(lambda: {k: v for d in (x, y) for k, v in d.items()} )) 1.163769006729126 >>> min(timeit.repeat(lambda: dict(itertools.chain(x.iteritems(),y.iteritems())))) 1.1614501476287842 >>> min(timeit.repeat(lambda: dict((k, v) for d in (x, y) for k, v in d.items()))) 2.2345519065856934在python3.5中
>>> min(timeit.repeat(lambda: {**x, **y})) 0.4094954460160807 >>> min(timeit.repeat(lambda: merge_two_dicts(x, y))) 0.7881555100320838 >>> min(timeit.repeat(lambda: {k: v for d in (x, y) for k, v in d.items()} )) 1.4525277839857154 >>> min(timeit.repeat(lambda: dict(itertools.chain(x.items(), y.items())))) 2.3143140770262107 >>> min(timeit.repeat(lambda: dict((k, v) for d in (x, y) for k, v in d.items()))) 3.2069112799945287
總結#
以上是Python中如何合併兩個字典的範例分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

SublimeText3漢化版
中文版,非常好用

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具