3.5 dictionary
Another data type defined in python is dictionary. In other languages, dictionaries may be defined as "Composite memories" or "Composite arrays ". Unlike sequences that can be indexed by numbers, it is a constant type of keyword keys in the dictionary. String and number are common keywords. If the tuples only contain strings, arrays, or duplicates, The tuples can also act as keywords. However, if the tuples directly or indirectly contain variable objects, the tuples cannot be keywords.
You cannot use the list as a keyword, because the list can change its own value when it is used in index assignment, slice assignment, and method append () and extend.
Think of the dictionary as a pair of unordered key: value pairs, and the only keyword in a dictionary is a very correct understanding of the dictionary. You can use the del method to delete a pair of key-value pairs. When you use an existing key to save a value, the associated value is discarded. An error occurs when no keyword is used to obtain the value.
List (d. keys () can obtain a list of all the keywords in the dictionary. the keywords in the list are unordered. If you want to sort the keywords, you can use sorted (d. keys ()). you can use the in keyword to check whether a single keyword is in the dictionary.
The following is a simple example of using a dictionary:
>>> Tel = {'jack': 4098, 'sape ': 4139}
>>> Tel ['guid'] = 4127
>>> Tel
{'Sape ': 4139, 'guide': 4127, 'jack': 4098}
>>> Tel ['jack']
4098
>>> Del tel ['sape ']
>>> Tel ['irv'] = 4127
>>> Tel
{'Guide': 4127, 'irv': 4127, 'jack': 4098}
>>> List (tel. keys ())
['Irv', 'guid', 'jack']
>>> Sorted (tel. keys ())
['Guide', 'irv', 'jack']
>>> 'Guide' in tel
True
>>> 'Jack' not in tel
False
In the dictionary, you can use the dict () constructor to define a dictionary directly from the sequence containing key-vlaue.
>>> Dict ([('sape ', 4139), ('guid', 4127), ('jack', 4098)])
{'Sape ': 4139, 'jack': 4098, 'guid': 4127}
In addition, the dictionary uses a composite expression to create a dictionary from a random expression of key and value.
>>>{ X: x ** 2 for x in (2, 4, 6 )}
{2: 4, 4: 16, 6: 36}
When the keyword is a simple string, you can use the keyword parameter to directly specify the object, which is sometimes easier.
>>> Dict (sape = 4139, guido = 4127, jack = 4098)
{'Sape ': 4139, 'jack': 4098, 'guid': 4127}