Inventory of common usage of dict and set in Python programming

Click on " Advanced Go Language Learning " above to follow

Reply to " Go Language " to receive a total of 10 e-books from beginner to advanced

now

day

Chickens

soup

Only in this mountain, the clouds do not know where.

One, dict

Python has a built-in dictionary: dict is supported. The full name of dict is dictionary, which is also called map in other languages. It uses key-value storage and has extremely fast search speed.

Example: Suppose you want to find the corresponding grade according to the name of the classmate. If you use a list to implement it, you need two lists:

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

Define a name. To find the corresponding score, you must first find the corresponding position in the names, and then retrieve the corresponding score from the scores. The longer the list, the longer it takes.

If implemented with dict, only a "name"-"score" comparison table is needed, and the results are directly searched based on the name. No matter how big the table is, the search speed will not slow down.

Example:

d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Michael'])

1. Why is the dict search speed so fast?

dict is to 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. No matter which word is searched, the search speed is very fast and will not slow down as the size of the dictionary increases.

The method of putting data into the dict, in addition to the designation during initialization, can also be put into the key:

d['Adam'] = 67
print(d['Adam'])

Since a key can only correspond to one value, if you put a key into value multiple times, the following value will wash out the previous value:

d['Jack'] = 90
d['Jack'] = 88
print(d['Jack']) #多次对一个key放入value,后面的值会把前面的值冲掉:显示后面修改的值

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

print( d['Thomas'])

2. There are two ways to avoid the error that the key does not exist.

2.1. It is to judge whether the key exists by in

print('Thomas' in d)

2.2. It 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')
print(d.get('Thomas', -1))

Note:

Python's interactive command line does not display the result when None is returned.

To delete a key, use the pop(key) method, and the corresponding value will also be deleted from the dict:

d.pop('Bob')
print(d)

3. Compared with list, dict has the following characteristics:

  1. The search and insertion speed is extremely fast, and it will not increase with the increase of the key;

  2. Need to take up a lot of memory, a lot of waste of memory. The opposite of list:

  3. The time to find and insert increases with the increase of elements;

  4. It occupies a small space and wastes little memory. Therefore, dict is a way to exchange space for time.

Two, set

Set is similar to dict. It is also a set of keys, but does not store value. Since the key cannot be repeated, there is no duplicate key in the set.

To create a set, you need to provide a list as an input set:

s = set([1, 2, 3])
print(s)

The incoming parameter [1, 2, 3] is a list, and the displayed {1, 2, 3} just tells the set that there are three elements of 1, 2, 3, and the order of display does not mean that the set has Ordered. .

Repeated elements are automatically filtered in the set:

s = set([1, 1, 2, 2, 3, 3])
print(s)

You can add elements to the set through the add(key) method, and you can add them repeatedly, but it will not have any effect:

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

Elements can be deleted through the remove(key) method:

s.remove(2)
print(s)

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

s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
print(s1 & s2)


print(s1 | s2)

The difference between set and dict

The only thing is that the corresponding value is not stored. However, the principle of set is the same as that of dict. Therefore, variable objects cannot be placed in the same way. Because it is impossible to judge whether two variable objects are equal, there is no guarantee that there will be no duplication in the set. element". Try to put the list into the set and see if it will report an error.

Third, discuss immutable objects again

str is an immutable object, and list is a mutable object. For mutable objects, such as list, if you operate on the list, the contents of the list will change.

Example:

a = ['c', 'b', 'a']
a.sort() # a['a', 'b', 'c']
print(a)

And for immutable objects, such as str, operate on str:

a = 'abc'
b = a.replace('a', 'A')
print(b)
print(a)

Note:

For an immutable object, calling any method of the object itself will not change the content of the object itself. Instead, these methods create a new object and return it, thus ensuring that the immutable object itself is always immutable.

Four, summary

Based on the Python foundation, this article introduces how to use dict and set. The dict with key-value storage structure is very useful in Python. It is important to choose immutable objects as keys. The most commonly used keys are strings.

Through the explanation of each module, the analysis of the case, the points that need to be paid attention to in the actual case, and the difficulties encountered, provide a detailed explanation plan.

Using JavaScript language can help readers understand better, and hope to help you learn better.

------------------- End -------------------

Recommendations of previous wonderful articles:

Welcome everyone to like , leave a message, forward, reprint, thank you for your company and support

If you want to join the Go learning group, please reply in the background [ Enter the group ]

Thousands of rivers and mountains are always in love, can you click [ Looking ]

Guess you like

Origin blog.csdn.net/pdcfighting/article/details/113903827