This paper describes the common methods and efficiency comparisons of Python merging two dictionaries. Share to everyone for your reference. The specific analysis is as follows:
The following code gives an example of 5 ways to merge two dictionaries, and a simple performance test
#!/usr/bin/python Import Time Def F1 (D1, D2): return Dict (D1, **D2) def f2 (D1, D2): return Dict (D1.items () + d2.it EMS ()) def f3 (D1, D2): d = d1.copy () d.update (D2) return D def f4 (D1, D2): d1.update (D2) return D1 de F f5 (D1, D2): d = dict (D1) d.update (D2) return D def f6 (D1, D2): return (Lambda A, B: Lambda A_copy:a_c Opy.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 '} D Ic2 = {' A ': ' AA ', ' B ': ' BB ', ' C ': ' CC '} f (Dic1, dic2) et = Time.time ()
In addition to the F4 method, which causes disruptive changes to the dictionary D1, several other methods are to return the merged results as a new dictionary.
Here are the test results:
You can see that F4 is the most efficient, and it is recommended to use the F4 method if you do not need to retain the original dictionary.
Hopefully this article will help you with Python programming.