Dictionary (dictionary). Like lists, dictionaries can also store multiple elements . This object, which stores multiple elements, is called a container (container)
Basic concepts
Common ways to create dictionaries:
>>>dic = {' Tom ': One, ' Sam ': +, ' Lily ': 100}
>>>print type (DIC)
Dictionaries and tables are similar in that they contain multiple elements, each separated by commas. But the dictionary element contains two parts, the key and the value, the common is to use a string to represent the key, or the number or truth to represent the key (the immutable object can be used as the key). The value can be any object. The keys and values correspond to one by one.
For example, ' Tom ' corresponds to one, ' Sam corresponds to ', ' lily ' corresponds to 100
Unlike tables, the elements of a dictionary are not in order. You cannot reference the element by subscript. Dictionaries are referenced by keys.
>>>print dic[' Tom ']
>>>dic[' tom '] = 30
>>>print DIC
To build a new empty dictionary:
>>>dic = {}
>>>print DIC
A way to add a new element to the dictionary:
>>>dic[' Lilei '] = 99
>>>print DIC
Here, we refer to a new key and give it the corresponding value.
Circular invocation of dictionary elements
DIC = {'lilei'Lily'sam' Tom': All -in-in dic :Print Dic[key]
In the loop, each key of the dict is extracted and given to the key variable.
With the result of print, we can confirm again that the elements in DIC are not sequential
Common methods of dictionaries
>>>print Dic.keys () # Returns all the keys of DIC
>>>print dic.values () # Returns all values of DIC
The above list is presented in the form of
>>>print dic.items () # Returns all elements of DIC (key-value pairs) ...
Presented in the form of: key-value pairs form a list of tuples, [(' Lily ', 123), (' Jhon ', "), (' Jack '," Max "), (' Tom ', 89)]
>>>dic.clear () # empty dic,dict changed to {}
In addition, there is a very common usage:
>>>del dic[' Tom '] # remove DiC's ' tom ' element
Del is a reserved keyword in python that is used to delete an object.
Like a table, you can query the total number of elements in the dictionary with Len ().
>>>print (Len (DIC))
"Python" dictionary