Python's dict and set

Source: Internet
Author: User
Tags stdin

 dictpython built-in dictionary: dict support, Dict full name dictionary, also known as map in other languages, using key-value (Key-value) storage, with extremely fast search speed.   For example, suppose you want to find the corresponding score according to the name of the classmate, if you implement it with list, you need two list: names = [' Michael ', ' Bob ', ' Tracy ']scores = [95, 75, 85] given a name, To find the corresponding results, first to find the corresponding position in the names, and then remove the corresponding results from scores, the longer the list, the longer the time.   If implemented with Dict, only need a "name"-"score" of the table, directly based on the name of the results, no matter how large the table, the search speed will not be slow. Write a dict in Python as follows: >>> d = {' Michael ': ", ' Bob ':", ' Tracy ': 85}>>> d[' Michael ') 95 Why dict look so fast? Because the implementation principle of dict and look dictionary is the same. Suppose the dictionary contains 10,000 characters, we need 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 search the dictionary's index table (such as the radical table) for the corresponding page number, and then directly to the page to find the word. Whichever word you look for, this is very fast and does not slow down as the dictionary size increases.  dict is the second implementation, given a name, such as ' Michael ', Dict can directly calculate Michael's corresponding storage Score "page number", that is, 95 of the memory address of the number stored, directly out, so the speed is very fast.   You can guess, this kind of key-value storage method, when put in, must calculate the place of value according to the key, so that the time can be obtained by key directly to the value.   Put the data into the Dict method, in addition to the initialization of the specified, you can also put the key into: >>> d[' adam ') = 67>>> d[' Adam '] 67 because a key can only correspond to one value, so, multiple times to a key put value, the following value will be the previous value to wash off: >>> d[' Jack '] =90>>> d[' Jack ']90>>> d[' jack '] = 88>>> d[' Jack ']88 if key does not exist, Dict will error: >>> d[ ' Thomas ']traceback (most recent call last):  File "<stdin>", line 1, in <module>keyerror: ' Thomas ' to avoid key A non-existent error, there are two ways, one is to determine whether the key exists: >>> ' Thomas ' in Dfalse Two is provided by Dict the Get method, if key does not exist, you can return none, Or your own designated value: >>> D.get (' Thomas ') >>> d.get (' Thomas ',-1)-1 Note: When you return to none, the interactive command line for Python does not display the results.   To delete a key, using the Pop (key) method, the corresponding value will also be removed from Dict: >>> d.pop (' Bob ') 75>>> d{' Michael ': 95, ' Tracy ': 85} It is important to note that the order of Dict internal storage is not related to the order in which key is placed.   and list comparison, Dict has the following several characteristics: 
    1. The speed of finding and inserting is very fast and will not slow with the increase of key;
    2. It takes a lot of memory, and it wastes a lot of memory.
And the list is the opposite:
    1. The time to find and insert increases as the element increases;
    2. Small footprint and little wasted memory.
So, Dict is a way of exchanging space for time.  dict can be used in many places where high-speed lookups are needed, almost everywhere in Python code, it is important to use dict correctly, and the first thing to keep in mind is that the Dict key must be an immutable object.   This is because Dict calculates the storage location of value based on key, and if each calculation of the same key results in a different result, the dict interior is completely chaotic. The algorithm for calculating the position by key is called the hash Algorithm (hash).   to ensure the correctness of the hash, the object as a key can not be changed. In Python, strings, integers, and so on are immutable, so you can safely use them as keys. The list is mutable and cannot be used as key: >>> key = [1, 2, 3]>>> d[key] = ' A list ' Traceback (most recent call last): &nbsp ; File "<stdin>", line 1, in <module>typeerror:unhashable type: ' List ' setset is similar to Dict and is also a set of keys, but does 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 set: >>> s = Set ([1, 2, 3]) >>> S{1, 2, 3} Note that the parameters passed in [1, 2, 3] are a list, And the displayed {1, 2, 3} just tells you that this set has 3 elements in the inside of a single element, and the order shown does not indicate that the set is ordered.   Repeating elements are automatically filtered in set: >>> s = Set ([1, 1, 2, 2, 3, 3]) >>> S{1, 2, 3} The add element can be added to the set by means of the Add (key) method, which can be added repeatedly, But it won't work.: >>> S.add (4) >>> s{1, 2, 3, 4}>>> S.add (4) >>> s{1, 2, 3, 4} via remove (key) method to delete an element: >>> S.remove (4) >>>S{1, 2, 3}set can be seen as a mathematical set of unordered and non-repeating elements, therefore, two sets can do the mathematical sense of intersection, and set the operation: >>> S1 = set ([1, 2, 3]) >>> s2 = Set ([2, 3, 4]) >>> S1 & s2{2, 3}>>> s1 | The only difference between S2{1, 2, 3, 4}set, and dict is that it does not store the corresponding value, but the principle of set is the same as dict, so it is also not possible to put mutable objects, because it is impossible to determine whether two mutable objects are equal, and there is no guarantee that "there will be no duplicate elements" inside the set. Try putting the list in set to see if it will give an error.   re-discussing non-mutable objects above we have said that Str is an immutable object, and list is a mutable object.   for mutable objects, such as list, to manipulate the list, the contents of the list will change, such as: >>> a = [' C ', ' B ', ' A ']>>> a.sort () >> > a[' A ', ' B ', ' C '] and for non-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 change the ' ABC ', but the variable A is still ' abc ', how should it be understood?   We first change the code to the following so: >>> 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 actually it means that a is itself a variable, it points to the content of the object is ' abc ':   when we call A.replace (' A ', ' a '), Actually the call method replace is 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 if we use the variable B to point to theThe new string, it is easy to understand that the variable a still points to the original string ' abc ', but the variable B is pointing to the new string ' abc ':   So, for the invariant object, the call to the object itself of any method, will not change the contents of the object itself. Instead, these methods create a new object and return it, ensuring that the immutable object itself is always immutable.   Summary dict using the Key-value storage structure is very useful in python, it is important to choose an immutable object as key, and the most commonly used key is a string. Although  tuple are immutable objects, try putting (1, 2, 3) and (1, [2, 3]) into dict or set and interpreting the results.  

Python's dict and set

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.