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