A, Dictionary (dictionary)
1. The dictionary (dictionary) is another very useful built-in data type in Python.
2, the list is an ordered combination of objects, the dictionary is an unordered collection of objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.
3. The dictionary is a type of mapping, and the dictionary is identified with "{}", which is an unordered key (key): The value pair collection.
4. Keys (key) must use the immutable type.
5. In the same dictionary, the key must be unique.
Second, examples
#!/usr/bin/python3
Dict = {}
dict[' One ' = "1-Rookie 1"
DICT[2] = "2-Rookie 2"
tinydict = {' name ': ' Runoob ', ' Code ': 1, ' site ': ' www.runoob.com '}
Print (dict[' one ') # output key is ' one ' value
Print (dict[2]) # Value for Output key 2
Print (tinydict) # Output a complete dictionary
Print (Tinydict.keys ()) # Output all keys
Print (Tinydict.values ()) # Outputs all values
The result of the above example output:
1-Rookie 1
2-Rookie 2
{' name ': ' Runoob ', ' site ': ' www.runoob.com ', ' Code ': 1}
Dict_keys ([' Name ', ' site ', ' Code '])
Dict_values ([' Runoob ', ' www.runoob.com ', 1])
The constructor Dict () can build the dictionary directly from the key-value pair sequence as follows:
Instance
>>>dict (' Runoob ', 1), (' Google ', 2), (' Taobao ', 3)])
{' Taobao ': 3, ' Runoob ': 1, ' Google ': 2}
>>> {x:x**2 for x in (2, 4, 6)}
{2:4, 4:16, 6:36}
>>> dict (runoob=1, google=2, taobao=3)
{' Taobao ': 3, ' Runoob ': 1, ' Google ': 2}
In addition, the dictionary type has some built-in functions, such as clear (), keys (), values (), and so on.
Attention:
(1) A dictionary is a type of mapping whose elements are key-value pairs.
(2) The dictionary keyword must be immutable and cannot be duplicated.
(3) Create an empty dictionary using {}.
Python Data Type-dictionary-016