前言
字典是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總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。
新聞熱點
疑難解答
圖片精選