Python uses dict and set

Source: Internet
Author: User

Dict

Python built-in dictionary: dict support, Dict full name dictionary, in other languages also become map, using key-value (Key-value) storage, with extremely fast search speed.

Suppose to find the corresponding score according to the name of the classmate, if the list is implemented, two lists are required:

names = ['Michael'Bob'Tracy '  = [95, 75, 85]

Given a name, to find the corresponding score, 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 the dict implementation, 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:

The implementation principle of dict is the same as that of dictionary search. 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 find the corresponding page number of the word in the dictionary's index table (such as the Radicals), and then go directly to the page to find the word. No matter which word you look for, the search speed is very fast. 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.

It can be guessed that this Key-value storage method, when put in, must be based on the key to calculate the storage location of value, so that the time can be obtained by key directly to the value.

The method of putting data into dict, in addition to being specified during initialization, can also be placed by key:

Since key can only correspond to one value, the value is placed on a key more than once, and subsequent values flush out the previous value.

If key does not exist, Dict will get an error.

To avoid a key that does not exist, there are two ways to determine whether a key exists by using in:

The second is the Get method provided by Dict, if key does not exist, you can return none, or the value you specified:

Note that the interactive command line of Python does not display the results when none is returned.

To delete a key, use the Pop (key) method, and the corresponding value will be removed from the dict.

It is important to note that the order of Dict internal storage is not related to the order in which key is placed.

Compared with list, Dict has the following features:

① Find and insert the speed is very fast, will not be slow with the increase of key;

② requires a lot of memory and a lot of wasted memory.

And the list is the opposite:

① the time to find and insert increases as the element increases;

② occupies little space and consumes little memory.

So, Dict is a way of exchanging space for time.

Dict can be used in many places where you need to tell the lookup, it's almost ubiquitous in Python code, it's important to use dict correctly, and the first thing to keep in mind is that dict and key must be immutable objects.

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 a key:

Set

A set is similar to a list and is 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 the input collection:

Note that the parameter passed in [three-to-one] is a list, and the real {x-man} only tells you that the set has 3 elements in the inside of it, and that the order shown does not indicate that the set is ordered. Repeating elements are automatically filtered in set

You can add elements to the set by using the Add (key) method, but you can add them repeatedly, but it won't work:

You can delete an element by using the Remove (key) method

Set can be regarded as a set of unnecessary and non-repeating elements in mathematical sense, so two sets can do the intersection and set of mathematical meanings.

The only difference between set and dict is that it does not store the corresponding value, but the set principle is the same as the dict, so it is also not possible to put mutable objects, because it is not possible to determine whether the two Mutable objects are equal, and there is no guarantee that there will be no duplicate elements inside the set.

Re-discussing non-mutable objects

Set is an immutable object, and list is a mutable object.

For mutable objects, such as list, the contents of the list will change as the list is manipulated.

For non-mutable objects, such as STR, to operate on Str

Although the string has a replace () method, it does change the ' ABC ', but the variable A is still ' abc ' and how is it understood?

A is a variable, and ' abc ' is a String Object! Sometimes, we often say that the content of object A is ' abc ', but in fact it means that a is itself a variable, it points to the content of the object is ' ABC ';

' ABC '>>> b = a.replace ('a'a')> >> b'abc'>>> a'ABC '

When we call A.replace (' A ', ' a '), the actual calling 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 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 an immutable object, any method that invokes the object itself does not change the contents of the object itself. Instead, these methods create a new object return, which guarantees that the immutable object itself will never be mutable.

Python uses dict and set

Related Article

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.