Vamei Source: Http://www.cnblogs.com/vamei Welcome reprint, Please also keep this statement. Thank you!
Basic concepts, especially objects and classes, are described in the basic tutorials.
The advanced tutorial further expands on the basic tutorials to illustrate Python details. Hopefully, after the advanced tutorial, you have a more comprehensive understanding of python.
As we said before, the list is a class in Python. A particular table, such as NL = [1,3,8], is an object of this class. We can invoke some methods of this object, such as Nl.append (15).
We are going to introduce a new class, 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 ': 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 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
>>>print dic.items () # Returns all elements of DIC (key-value pairs)
>>>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))
Summarize
Each element of the dictionary is a key-value pair. element has no order.
DIC = {' Tom ': One, ' Sam ': +, ' Lily ': 100}
dic[' tom '] = 99
For key in DIC: ...
Del, Len ()
Python Advanced 01 Dictionary