Dict
Python has a built-in dictionary: dict support, Dict full name dictionary, also known as a map in other languages, using key-value (Key-value) storage, with extremely fast lookup speed.
For example, suppose you want to find the corresponding results according to your classmates ' names, and if you use list, you need two list:
names = [' Michael ', ' Bob ', ' Tracy ']
scores = [95, 75, 85]
Given a name, to find the corresponding results, the first to find the corresponding position in the names, and then take out the corresponding results from scores, the list the longer, time-consuming longer.
If you use Dict to achieve, only need a "name"-"performance" of the table, directly based on the name to find results, no matter how big the watch, the search speed will not be slow. Write a dict in Python as follows:
>>> d = {' Michael ': ' Bob ': $, ' Tracy ':}
>>> d[' Michael ']
95
Why is dict looking so fast? Because the principle of dict and dictionary is the same. If the dictionary contains 10,000 Chinese characters, we have to look up a word, one way is to turn the dictionary back from the first page, until we find the word we want, this method is to find the element in the list method, the larger the list, the slower the lookup.
The second method is to first in the Dictionary index table (such as the Radicals) to check the corresponding page number, and then directly to the page, find the word, no matter what word to find, the search speed is very fast, not as the size of the dictionary to increase and slow.
Dict is the second way to implement, given a name, such as ' Michael ', Dict can directly calculate Michael's corresponding "page number" of the storage, which is 95 of the number of memory address, directly out, so the speed is very fast.
As you can guess, this kind of key-value storage, in the time, must be based on key to calculate the location of value, so that the time to take the key directly to the value.
Put the data into the Dict method, in addition to the initialization of the specified, but also through the key into:
>>> d[' adam ' =
>>> d[' Adam ']
67
Since a key can only correspond to one value, a key is placed in value multiple times, followed by a value that flushes the previous value:
>>> d[' jack '] =
>>> d[' Jack '] [
>>> d[' jack '] =
>>> d[' Jack ']
88
If key does not exist, Dict will complain:
>>> d[' Thomas ']
traceback (most recent call last):
File "<stdin>", line 1, in <module>< C14/>keyerror: ' Thomas '
To avoid key errors, there are two ways to determine whether a key exists through in:
>>> ' Thomas ' in D
False
The second is the Get method provided by Dict, if the key does not exist, you can return none or the value you specify:
>>> d.get (' Thomas ')
>>> d.get (' Thomas ',-1)
-1
Note: Python's interactive command line does not display results when none is returned.
To delete a key, using the Pop (key) method, the corresponding value is also removed from the dict:
>>> d.pop (' Bob ')
+
>>> d
{' Michael ': $, ' Tracy ': 85}
It is important to note that the order in which the dict is stored is not related to the order in which the key is placed.
Compared with list, Dict has the following features:
- Find and insert the speed is very fast, does not increase as the key increases;
- Requires a large amount of memory, memory waste more.
And the list is the opposite:
- The time to find and insert increases as the element increases;
- Small footprint, little waste of memory.
So, Dict is a way of exchanging space for time.
Dict can be used in many places where there is a need for high-speed lookups, almost everywhere in Python code, and it is important to use dict correctly, and the first thing to remember is that dict key must be immutable.
This is because Dict calculates the storage location of value based on key, and if the same key is calculated differently each time, the dict is completely messed up. This algorithm, which uses the key to compute the position, is called a hash algorithm.
To ensure the correctness of the hash, the object as a key cannot be changed. In Python, strings, integers, and so on are immutable, so it's safe to be a key. The list is variable and cannot be a key:
>>> key = [1, 2, 3]
>>> d[key] = ' A list '
Traceback (most recent call last):
File "<stdin > ", Line 1, in <module>
typeerror:unhashable type: ' List '
Set
Set and dict are similar, and are collections of a set of keys, but do not store value. Because key cannot be duplicated, there is no duplicate key in set.
To create a set, you need to provide a list as an input collection:
>>> s = Set ([1, 2, 3])
>>> s
set ([1, 2, 3])
Note that the parameters passed in [1, 2, 3] are a list, and the display set ([1, 2, 3]) simply tells you that there are 3 elements inside the set, and that [] does not indicate that this is a list. 1,2,3
Repeating elements are automatically filtered in set:
>>> s = Set ([1, 1, 2, 2, 3, 3])
>>> s
set ([1, 2, 3])
The Add (key) method allows you to add elements to the set, which you can add repeatedly but without effect:
>>> S.add (4)
>>> s
set ([1, 2, 3, 4])
>>> s.add (4)
>>> s
set ([ 1, 2, 3, 4])
You can delete an element by using the Remove (key) method:
>>> S.remove (4)
>>> s
set ([1, 2, 3])
Set can be regarded as a mathematical sense of unordered and no repeating elements of the set, therefore, two sets can do the mathematical sense of intersection, and set and other operations:
>>> S1 = set ([1, 2, 3])
>>> s2 = Set ([2, 3, 4])
>>> S1 & S2
Set ([2, 3])
>>> S1 | S2
Set ([1, 2, 3, 4])
The only difference between set and dict is that there is no storage of the corresponding value, but the principle of set is the same as that of dict, so the same cannot be put into a mutable object, because it is impossible to tell whether two mutable objects are equal and there is no guarantee that there will be no duplicate elements within the set Try putting the list in set to see if there is an error.
Re-discussion on mutable objects
As we said above, Str is invariant, and list is a mutable object.
For variable objects, such as list, the list is manipulated, and the contents within the list are changed, such as:
>>> a = [' C ', ' B ', ' a ']
>>> a.sort ()
>>> a
[' A ', ' B ', ' C ']
And for mutable objects, such as STR, to operate on STR:
>>> a = ' abc '
>>> a.replace (' A ', ' a ')
' abc '
>>> a
' abc '
Although the string has a replace () method, it does turn out ' abc ', but the variable a finally remains ' abc ', how should it be understood?
Let's first change the code to look like this:
>>> a = ' abc '
>>> b = a.replace (' A ', ' a ')
>>> b
' abc '
>>> A
' abc '
Always keep in mind that a is a variable, and ' abc ' is a String Object! Sometimes, we often say that the content of object A is ' abc ', but it actually means that a is a variable in itself, and the object it points to is ' abc ':
When we call A.replace (' A ', ' a '), actually invoking method replace is acting on the string object ' abc ', and this method, although named Replace, does not change the contents of the string ' abc '. Instead, the Replace method creates a new string ' abc ' and returns, and if we point to the new string with variable B, it's easy to understand that variable a still points to the original string ' abc ', but the variable B points to the new string ' abc ':
Therefore, for invariant objects, any method that invokes the object itself does not change the content of the object itself. Instead, these methods create new objects and return them, thus ensuring that immutable objects themselves are immutable.
Summary
Dict with Key-value storage structure is very useful in python, it is important to select immutable objects as key, the most common key is string.
Although tuple is invariant, try putting (1, 2, 3) and (1, [2, 3]) into dict or set, and interpreting the results.