A comparison of common methods and efficiencies of Python merging two dictionaries

Source: Internet
Author: User
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.

  • 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.