Python合并兩個字典的常用方法與效率比較

來源:互聯網
上載者:User

Python合并兩個字典的常用方法與效率比較

   本文執行個體講述了Python合并兩個字典的常用方法與效率比較。分享給大家供大家參考。具體分析如下:

  下面的代碼舉例了5種合并兩個字典的方法,並且做了個簡單的效能測試

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

#!/usr/bin/python

import time

def f1(d1, d2):

return dict(d1, **d2)

def f2(d1, d2):

return dict(d1.items() + d2.items())

def f3(d1, d2):

d = d1.copy()

d.update(d2)

return d

def f4(d1, d2):

d1.update(d2)

return d1

def f5(d1, d2):

d = dict(d1)

d.update(d2)

return d

def f6(d1, d2):

return (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(d1, d2)

def f7(d1, d2):

d = {}

d.update(d1)

d.update(d2)

return d

def t(f, n):

st = time.time()

for i in range(1000000):

dic1 = {'a':'AA','b':'BB','c':'CC'}

dic2 = {'A':'aa','B':'bb','C':'cc'}

f(dic1, dic2)

et = time.time()

print '%s cost:%s'%(n, et-st)

t(f1, 'f1')

t(f2, 'f2')

t(f3, 'f3')

t(f4, 'f4')

t(f5, 'f5')

t(f6, 'f6')

t(f7, 'f7')

  除了f4方法會對字典d1造成破壞性修改之外,另外的幾種方法都是把合并的結果作為新的字典返回。

  下面是測試結果:

  ?

1

2

3

4

5

6

7

f1 cost:2.382999897

f2 cost:4.45399999619

f3 cost:3.02100014687

f4 cost:1.73000001907

f5 cost:2.3710000515

f6 cost:2.89700007439

f7 cost:2.35600018501

  可以看出f4最為高效,如果不需要保留原字典的話推薦使用f4方法。

  希望本文所述對大家的Python程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.