[Python] This article will help you master the collection of data containers and dictionaries

Table of contents:

1. Collection

Thinking: We are currently exposed to three data containers: list, tuple, and string. Why do you need to learn new collection types when it basically meets most usage scenarios?

Analysis through characteristics:
(1) The list can be modified, supports repeated elements and is ordered
(2) Tuples and strings cannot be modified,support repeated elements and are ordered

Have you seen any limitations?

The limitation is: they all support repeated elements

If the scene requires deduplication of content, lists, tuples, and strings are inconvenient.

The main feature of collections is: does not support duplication of tuples (it has its own deduplication function), and the content is out of order


1. Definition of set

Basic syntax:

# 定义集合字面量
{元素,元素,......,元素}

# 定义集合变量
变量名称 = {元素,元素,......,元素}

# 定义空集合
变量名称 = set()

 The definitions are basically the same as lists, tuples, strings, etc.:

Use column table[ ​ ]

Use of original system( )

String usage" "

Set usage{ }


 2. Common operations on collections

First of all, because the set is unordered, the set does not support: subscript index access but the set, like the list, is allowed to be modified. , so let’s take a look at how to modify the collection

serial number operate effect
1 collection.add(element) Add an element to the collection
2 Collection remove(element) Removes the specified element from the collection
3 collection.pop() Randomly remove an element from the set
4 set.clear() Clear the collection
5 set 1.difference(set 2) Get a new set, which contains the difference set of two sets. The contents of the original two sets remain unchanged.
6 set 1.differenceupdate(set 2) In set 1, delete the elements that exist in set 2. Set 1 is modified, and set 2 remains unchanged.
7 Set1.union(set2) Get a new collection containing all the elements of the two collections. The contents of the original two collections remain unchanged.
8 len(set) Get an integer that records the number of elements in the set
(1)Add new elements

Syntax:Collection.add(element)Add the specified element to the collection

Result: The collection itself is modified, new elements are added

my_set = {"Hello", "World"}
my_set.add("bite")
print(my_set)  # 结果:{'World', 'bite', 'Hello'}(顺序可能会变)
(2) Remove elements

Syntax:Collection.remove(element), remove the specified element from the collection

Result: The collection itself is modified, elements are removed

my_set = {"Hello", "World"}
my_set.remove("World")
print(my_set)  # 结果:{'Hello'}
 (3) Randomly remove elements from the set

Syntax:set.pop(), function, randomly remove an element from the set

Result: A result of one element will be obtained. At the same time the collection itself is modified and elements are removed

my_set = {"Hello", "World"}
element = my_set.pop()
print(my_set)  # 结果:{'Hello'}
print(element)  # 结果:World
(4) Clear the collection

Syntax:Collection.clear(), function, clear the collection

Result: The collection itself is emptied

my_set = {"Hello", "World"}
my_set.clear()
print(my_set)  # 结果:set()
 (5) Take the difference set of two sets

Syntax:Set 1.difference(set 2), Function: Take the difference between set 1 and set 2 (set 1 has and Not available in set 2)

Result:Get a new set, set 1 and set 2 remain unchanged

set1 = {1, 2, 3}
set2 = {1, 5, 6}
set3 = set1.difference(set2)
print(set3)  # 结果:{2, 3}
print(set2)  # 结果:{1, 5, 6}
print(set1)  # 结果:{1, 2, 3}
(6) Eliminate the difference between two sets

Syntax:Set 1.difference_update(set 2)

Function: Compare set 1 and set 2,In set 1, delete the same elements as set 2

Result: Set 1 is modified, set 2 remains unchanged

set1 = {1, 2, 3}
set2 = {1, 5, 6}
set1.difference_update(set2)
print(set1)  # 结果:{2, 3}
print(set2)  # 结果:{1, 5, 6}
(7) Merge 2 sets

Language:Set 1.union(Set 2)

Function:Combine set 1 and set 2 into a new set

Result: A new set is obtained, and set 1 and set 2 remain unchanged.

set1 = {1, 2, 3}
set2 = {1, 5, 6}
set3 = set1.union(set2)
print(set3)  # 结果:{1, 2, 3, 5, 6}
print(set1)  # 结果:{1, 2, 3}
print(set2)  # 结果:{1, 5, 6}

2. Dictionary

Thinking: The teacher has a list that records the names and total test scores of the students. Now it needs to be entered into the program through Python, and the students can be retrieved by their names Score, thus introducing the dictionary, using the dictionary you can use the key to extract the Value operation

1.Dictionary definition

Dictionary definition, also uses { }, but the stored elements are one by one: Key-value pair, the following syntax:

# 定义字典字面量
{key: value, key: value, ......, key: value}

# 定义字典变量
 my_dict = {key: value, key: value, ......, key: valuel}

# 定义空字典
my_dict = {}    # 空字典定义方式1
my_dict = dict()  # 空字典定义方式2

Note: Repeated Keys are not allowed in the dictionary. Repeated additions are equivalent to overwriting the original data

# 定义重复Key的宇典
my_dict1 = {"王力鸿": 99,"王力鸿": 88,"林俊节": 77}
print(f"重复key的字典的内容是:{my_dict1}")

# 结果:重复key的字典的内容是:{'王力鸿':88,林俊节':77}

2. Acquisition of dictionary data

Dictionaries are the same as sets and cannot be indexed using subscripts.

But the dictionary can obtain the corresponding Value through the Key value

# 语法,字典[Key]可以取到对应的value
stu_score = {"李四": 99, "张三": 88,"王二麻子": 77}
print(stu_score["李四"])   # 结果:99
print(stu_score["张三"])   # 结果:88
print(stu_score["王二麻子"])  # 结果:77

3. Nesting of dictionaries

DictionaryKey and Value can be any data type(Key cannot be a dictionary) a>

Then, it shows that dictionaries can be nested

The requirements are as follows: Record students’ examination information in various subjects

stu_score_dict = {
    "王力鸿": {
        "语文": 77,
        "数学": 66,
        "英语": 33
    }, "周杰轮": {
        "语文": 88,
        "数学": 86,
        "英语": 55
    }, "林俊节": {
        "语文": 99,
        "数学": 96,
        "英语": 66
    }
}
print(f"学生的考试信息是:{stu_score_dict}")

# 结果:学生的考试信息是:{'王力鸿': {'语文': 77, '数学': 66, '英语': 33}, '周杰轮': {'语文': 88, '数学': 86, '英语': 55}, '林俊节': {'语文': 99, '数学': 96, '英语': 66}}

Get data from nested dictionary:

score = stu_score_dict["周杰轮"]["语文"]
print(f"周杰轮的语文分数是:{score}")

# 结果:周杰轮的语文分数是:88

4. Common operations on dictionary

serial number operate effect
1 Dictionary[Key] Get the Value value corresponding to the specified Key
2 Dictionary[Key]=Value Add or update key-value pairs
3 Dictionary.pop(Key) Get the Value corresponding to the Key and delete the key-value pair of this Key in the dictionary
4 dictionary.clear() Clear dictionary
5 dictionary.keys() Get all the keys of the dictionary, which can be used in a for loop to traverse the dictionary
6 len (dictionary) Count the number of elements in a dictionary
(1) New elements

Syntax: Dictionary [Key] =Value, result: the dictionary is modified and new elements are added

my_dict1 = {"王力鸿": 88, "林俊节": 77}
# 新增,张学油的考试成绩
my_dict1['张学油'] = 66
print(my_dict1)

# 结果:{'王力鸿': 88, '林俊节': 77, '张学油': 66}
(2) Update elements

Syntax:Dictionary[Key]=Value, result: the dictionary is modified and the element is updated

Note: Dictionary Key cannot be repeated, so performing the above operation on the existing Key is to update the Value

my_dict1 = {"王力鸿": 88, "林俊节": 77}
my_dict1['王力鸿'] = 66
print(my_dict1)

# 结果:{'王力鸿': 66, '林俊节': 77}
(3) Delete elements

Syntax: Dictionary.pop(Key), Result: The Value of the specified Key is obtained, the dictionary is modified, and the data of the specified Key is Delete

my_dict1 = {"王力鸿": 88, "林俊节": 77}
value = my_dict1.pop("王力鸿")
print(value)   # 结果:88
print(my_dict1)  # 结果:{'林俊节': 77}
(4) Clear the dictionary

Syntax:Dictionary.clear(), result: the dictionary is modified and the elements are cleared

my_dict1 = {"王力鸿": 88, "林俊节": 77}
my_dict1.clear()
print(my_dict1)

# 结果:{}
(5) Get all keys of the dictionary

Syntax:Dictionary.keys(), can be used for loop to traverse the dictionary

# 获取全部的key
my_dict = {"周杰轮": 99, "王力鸿": 88, "林俊节": 77}
keys = my_dict.keys()
print(f"字典的全部keys是:{keys}")  # 结果:字典的全部keys是:dict_keys(['周杰轮', '王力鸿', '林俊节'])

# 遍历字典
# 方式一:通过获取到全部的key来完成遍历
for key in keys:
    print(f"字典的key是:{key}")
    print(f"字典的value是: {my_dict[key]}")

# 方式二:直接对字典进行for循环,每一次循环都是直接得到key
for key in my_dict:
    print(f"字典的key是:{key}")
    print(f"字典的value是: {my_dict[key]}")

5. Features of dictionary

After the above study of dictionaries, we can conclude that dictionaries have the following characteristics:

(1) Can accommodate multiple data

(2) Can accommodate different types of data

(3)Each piece of data is a KeyValue pair

(4)The Value can be obtained through the Key. The Key cannot be repeated (repetition will overwrite)

(5) Subscript index is not supported

(6) Can be modified (add or delete update elements, etc.)

(7) Supports for loop, but does not support while loop


That’s it for this content. You are welcome to communicate in the comment area or private messages. If you think what the author wrote is okay, or if you have gained something from it, please give me a one-click three-way link. Thank you very much!  

Guess you like

Origin blog.csdn.net/qq_73017178/article/details/134406890