Comparison of common methods and efficiency for merging two dictionaries in Python
This article describes the common methods and Efficiency Comparison of combining two dictionaries in Python. Share it with you for your reference. The specific analysis is as follows:
The following code illustrates five ways to merge two dictionaries and performs a simple performance test.
?
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': 'A', 'B': 'bb', 'C': 'cc '} Dic2 = {'A': 'A', '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 ') |
In addition to the destructive modification to the dictionary d1 by the f4 method, the combined result is returned as a new dictionary.
The test result is as follows:
?
1 2 3 4 5 6 7 |
F1 cost: 2.382999897 F2 cost: 4.45399999619 S3 cost: 3.02100014687 F4 cost: 1.73000001907 F5 cost: 2.3710000515 6 cost: 2.89700007439 F7 cost: 2.35600018501 |
It can be seen that f4 is the most efficient. If you do not need to retain the original dictionary, the f4 method is recommended.
I hope this article will help you with Python programming.