A method of implementing two dictionaries (dict) merging in Python _python

Source: Internet
Author: User
Tags in python

This article describes the implementation of the Python two dictionaries (dict) of the method of merging, share for everyone to reference. The specific methods are as follows:

The existing two dictionaries are dict as follows:

DICT1={1:[1,11,111],2:[2,22,222]}
dict2={3:[3,33,333],4:[4,44,444]}

Merging two dictionaries to get a similar:

{1:[1,11,111],2:[2,22,222],3:[3,33,333],4:[4,44,444]}

Method 1:

Dictmerged1=dict (Dict1.items () +dict2.items ())

Method 2:

Dictmerged2=dict (Dict1, **dict2)

Method 2 is equivalent to:

Dictmerged=dict1.copy ()
dictmerged.update (DICT2)

Or:

Dictmerged=dict (Dict1)
dictmerged.update (DICT2)

Method 2 is much faster than Method 1, with Timeit test as follows

$ python-m timeit-s ' dict1=dict2=dict ((i,i) for I in Range ()) ' Dictmerged1=dict (Dict1.items () +dict2.items ()) '
  10000 loops, best 3:20.7 usec
per loop $ python-m timeit-s ' dict1=dict2=dict ((i,i) to I in range ()) ' Dictme Rged2=dict (dict1,**dict2) '
  100000 loops, Best of 3:6.94 usec per loop
$ python-m timeit-s ' dict1=dict2=dict (i, i) for I in range (m) ' Dictmerged3=dict (Dict1) ' Dictmerged3.update (dict2) '
  100000 loops, Best of 3:7.09 usec per Loop
$ python-m timeit-s ' dict1=dict2=dict ((i,i) for I in Range ()) ' Dictmerged4=dict1.copy () ' DICTMERGED4.UPDA Te (dict2) '
  100000 loops, Best of 3:6.73 usec per loop

I hope this article will help you with your Python programming.

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.