The Basics tutorial introduces basic concepts, especially objects and classes.
The Advanced tutorial further expands the basic tutorial to illustrate the details of Python. Hopefully, after the advanced tutorials, you have a more comprehensive understanding of python.
As we said before, the list is a class in Python. A specific table, such as NL = [1,3,8], is an object of this class. We can call some methods of this object, such as Nl.append (15).
We are going to introduce a new class, A dictionary (dictionary). Like a list, a dictionary can store multiple elements. This object that stores multiple elements is called a container (container).
Basic concepts
Common ways to create dictionaries:
Copy Code code as follows:
>>>dic = {' Tom ': One, ' Sam ': #, ' Lily ': 100}
>>>print type (DIC)
A dictionary and a table are similar places that contain multiple elements, each of which is separated by commas. But the dictionary element contains two parts, a key and a value, which are commonly used as a string to denote a key, or a number or a truth to represent a key (immutable objects can be keys). The value can be any object. Key and value one by one correspond.
For example, in the above example, ' Tom ' corresponds to one, ' Sam corresponds to, ' lily ' corresponds to 100
Unlike a table, the elements of a dictionary have no order. You cannot reference elements by subscript. Dictionaries are referenced by keys.
Copy Code code as follows:
>>>print dic[' Tom '
>>>dic[' tom ' = 30
>>>print DIC
To build a new, empty dictionary:
Copy Code code as follows:
The method of adding a new element to the dictionary:
Copy Code code as follows:
>>>dic[' Lilei '] = 99
>>>print DIC
Here, we refer to a new key and give it the corresponding value.
Circular invocation of dictionary elements
Copy Code code as follows:
DiC = {' Lilei ': N, ' Lily ': M, ' Sam ': $, ' Tom ': 90}
For key in DIC:
Print Dic[key]
In the loop, each key of the dict is extracted and given to the key variable.
With the results of print, we can again confirm that the elements in DIC are not sequential.
Common methods of dictionaries
Copy Code code as follows:
>>>print Dic.keys () # Return all keys to DIC
>>>print dic.values () # Returns all values of DIC
>>>print dic.items () # Returns all elements of DIC (key-value pairs)
>>>dic.clear () # empty dic,dict changed to {}
There is also a very common usage:
Copy Code code as follows:
>>>del dic[' Tom '] # delete dic's ' tom ' element
The del is a reserved keyword in python for deleting objects.
Like a table, you can use Len () to query the total number of elements in the dictionary.
Copy Code code as follows:
Summarize
Each element of the dictionary is a key-value pair. element has no order.
Copy Code code as follows:
DIC = {' Tom ': One, ' Sam ': #, ' Lily ': 100}
dic[' Tom ' = 99
For key in DIC: ...
Del, Len ()