Python中如何優雅的合并兩個字典(dict)

來源:互聯網
上載者:User
字典是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 strings

Guido van Rossum 大神說了:宣告dict({}, {1:3})是非法的,因為畢竟是濫用機制。雖然這個方法比較hacker,但是太投機取巧了。

一些效能較差但是比較優雅的方法

下面這些方法,雖然效能差,但也比items方法好多了。並且支援優先順序。

{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 itertoolsz = dict(itertools.chain(x.iteritems(), y.iteritems()))

效能測試

以下是在Ubuntu 14.04上完成的,在Python 2.7(系統Python)中:

>>> 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.