Python learning -- 2.6 dictionaries and sets

dict

Python has a built-in dictionary: the support of dict, the full name of dict is dictionary, also called map in other languages, uses key-value (key-value) storage, and has extremely fast search speed.
For example, suppose you want to find the corresponding grades based on the names of your classmates. If you use a list to implement it, you need two lists:

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

If it is implemented with dict, only a "name"-"grade" comparison table is needed, and the results are directly searched according to the name. No matter how large the table is, the search speed will not slow down. Write a dict in Python as follows:

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95

Why is dict lookup so fast? Because the implementation principle of dict is the same as that of looking up a dictionary. Suppose the dictionary contains 10,000 Chinese characters, and we want to look up a certain 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. The larger the list, the slower the search.
The second method is to first look up the page number corresponding to the word in the index table of the dictionary (such as the radical table), and then directly turn to the page to find the word. This lookup is very fast no matter which word is looked for and does not slow down as the size of the dictionary increases.

Dict is the second implementation. Given a name, such as 'Michael', dict can directly calculate the "page number" corresponding to Michael's stored grades, that is, the memory address where the number 95 is stored, and directly take it out. So it's very fast.

As you can guess, in this key-value storage method, when you put it in, you must calculate the storage location of the value according to the key, so that you can get the value directly according to the key when you take it.

The method of putting data into dict, in addition to specifying it during initialization, can also be put in by key:

If the key does not exist, dict will report an error:

>>> d['Thomas']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Thomas'

To avoid the error that the key does not exist, there are two ways, one is to judge whether the key exists through in:

>>'a' in d
False

The second is through the get() method provided by dict. If the key does not exist, it can return None, or the value specified by itself:

d.get('a',-1)
Out[26]: -1
d.get('Bob',-1)
Out[28]: 75

To remove a key, use the pop(key) method, and the corresponding value is also removed from the dict:

>>> d.pop('Bob')
75
>>> d
{'Michael': 95, 'Tracy': 85}

It is important to note that the order in which the dict is stored has nothing to do with the order in which the keys are placed.

Compared with list, dict has the following characteristics:

The speed of searching and inserting is extremely fast, and it will not slow down with the increase of keys;
it takes up a lot of memory and wastes a lot of memory.
And list is the opposite:

The time to lookup and insert increases with the number of elements;
small footprint and very little wasted memory.
So, dict is a way to trade space for time.

So, dict is a way to trade space for time.

Dict can be used in many places where high-speed lookup is required. It is almost ubiquitous in Python code. It is very important to use dict correctly. The first thing to keep in mind is that the key of dict must be an immutable object.

This is because the dict calculates the storage location of the value according to the key. If the result obtained by calculating the same key each time is different, the interior of the dict will be completely confused. This algorithm for calculating the position by the key is called the hash algorithm (Hash).

To ensure the correctness of the hash, the object used as the key cannot be changed. In Python, strings, integers, etc. are immutable, so they can safely be used as keys. The list is mutable and cannot be used as a key

set

Similar to dict, set is also a collection of keys, but does not store value. Since keys cannot be repeated, there are no repeated keys in the set.
To create a set, provide a list as the input set.

>>> s = set([1, 2, 3])
>>> s
{1, 2, 3}

Elements can be added to the set through the add(key) method, which can be added repeatedly, but will not have any effect:

>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.add(4)
>>> s
{1, 2, 3, 4}

Elements can be removed with the remove(key) method:

>>> s.remove(4)
>>> s
{1, 2, 3}

A set can be regarded as a collection of unordered and non-repetitive elements in a mathematical sense. Therefore, two sets can perform operations such as intersection and union in a mathematical sense:

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325770608&siteId=291194637