[Python-dictionary usage] Three methods for creating a dictionary: python3
# Create an empty dictionary empty_dict = dict () print (empty_dict) # Use ** kwargs variable parameters to input keywords to create a dictionary a = dict (one = 1, two = 2, three = 3) print (a) # Pass in the iteratable object B = dict (zip (['one', 'two', 'three '], [1, 2, 3]) print (list (zip (['one', 'two', 'three '], [1, 2, 3]) print (B) # input iteratable Object c = dict ([('one', 1), ('two', 2), ('Three, 3)]) print (c) c1 = dict ([('one', 1), ('two', 2), ('Three ', 3), ('Three, 4 ), ('Three ', 5)]) print (c1) # If the key is repeated, its value is the value of the last repeated item.
# Input a ing object. Create a dictionary d = dict ({'one': 1, 'two': 2, 'three ': 3}) print (d) print (a = B = c = d)
Output:
{}{'one': 1, 'two': 2, 'three': 3}[('one', 1), ('two', 2), ('three', 3)]{'one': 1, 'two': 2, 'three': 3}{'one': 1, 'two': 2, 'three': 3}{'one': 1, 'two': 2, 'three': 5}{'one': 1, 'two': 2, 'three': 3}True
Knowledge point:
class dict(**kwarg)class dict(mapping, **kwarg)class dict(iterable, **kwarg)
In python, * arg indicates any number of unnamed parameters, whose type is tuple. ** kwargs indicates the keyword parameter, which is dict. Refer to [Python-parameters] * arg and ** kwargs parameter usage
In the official python documentation, it is stated that if an iteratable object is input, each item of the iteratable object must be iteratable and each item can have only two objects. The first object becomes the key of the new dictionary, and the second object becomes the value corresponding to its key. If the key already exists, its value is the value of the last repeated item.
# Using class dict (mapping, ** kwarg) to create a union dictionary will affect the union = dict (s1, ** s2) print (union) for different values of the same key)
Output:
{'d': 4, 'a': 3, 'e': 3, 'f': 4, 'c': 4, 'b': 3}
Knowledge point:
When calling a function, ** unpacks a dictionary in the form of a key/value pair, making it an independent keyword parameter. Refer to [Python-parameters] * arg and ** kwargs parameter usage