Comparison of efficiency instances of Python merging two dictionaries

Source: Internet
Author: User
This article mainly introduces the common methods and efficiency comparison of Python merging two dictionaries, and compares the common methods of Python merging dictionaries, and the need of friends can refer to the following

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 ()   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 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:

F1 cost:2.382999897 F2 cost:4.45399999619 f3 cost:3.02100014687 f4 cost:1.73000001907 f5 cost:2.3710000515 f6 cost:2.8970 0007439 F7 cost:2.35600018501

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.