Python dictionary merge, dictionary value, list to dictionary

Source: Internet
Author: User

1. Merging of dictionaries
#The first Python built-in method, Dict and * * Unpacking the way>>> A = {'name': 1,'b': 2}>>> B = {'name': 1,'C': 10}>>> C = Dict (A, * *b)>>>c{'name': 1,'b': 2,'C': 10}#the second update () method with the dictionary#Can be weighted with the elements in B to update the elements of a, the elements of a will change, but the memory address will not change>>>a{'a': 1,'b': 2,'C': 3,'D': 4}>>> B = {'C': 10,"D": 11}>>>A.update (b)>>>a{'a': 1,'b': 2,'C': 10,'D': 11}#The Third Kind (python3.5 above)>>> A = {'a': 1,"b": 2}>>> B = {'C': 3,"D": 4}>>> C = {**a,**B}>>>c{'a': 1,'b': 2,'C': 3,'D': 4}#Fourth Type#in python2.7>>> C = dict (A.items () +(B.items ())>>>c{'a': 1,'b': 2,'C': 3,'D': 4}#in Pyhton3>>> C = dict (List (A.items ()) +list (B.items ()))>>>c{'a': 1,'b': 2,'C': 3,'D': 4}
2. Get and SetDefault methods in dictionaries

Dictionaries are commonly used for Dict[key], but the problem is that when key does not exist in the dictionary, it will be an error, so if you do not want an error, you can use the Get and SetDefault methods.

>>> a{' A ': 1, ' B ': 2, ' C ': Ten, ' d ': 11}>>> a.setdefault (' C ', None) 10>>> a.setdefault (' W ', 1000) 1000>>> a{' A ': 1, ' B ': 2, ' C ': Ten, ' d ': One, ' W ': 1000}>>> a.get (' e ', ') 20>>> a{' A ': 1, ' B ': 2, ' C ': Ten, ' d ': One, ' W ': 1000}

3. Convert two lists to dictionaries

Use the built-in Zip method to convert two lists into zip objects, and then use the Dict method to convert the Zip object to a dictionary

>>> C = dict (Zip ([1, 2, 3, 4, 5, 6, 7], ['a','C','b','F','D','e','g']))>>>c{1:'a', 2:'C', 3:'b', 4:'F', 5:'D', 6:'e', 7:'g'}

Where a Zip object can be traversed with a for loop, it is found to be a tuple of pairs that correspond to indexes in two lists.

>>> a = Zip ([1,2],[3,4])>>> a for in A:      ... Print (i)     ... (1, 3) (2, 4)

Python dictionary merge, dictionary value, list to 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: 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.