Data container for basic learning in python: dict (dictionary, mapping)

Data container: dict (dictionary, mapping)

Why use a dictionary?
Because you can use a dictionary to implement the operation of extracting Value using key

dictionary definition

The definition of the dictionary also uses {}, but the stored elements are key-value pairs:
① Use {} to store the original, each element is a key-value pair
② Each key-value pair contains Key and Value ( separated by colon ) ③ Use commas
to separate key-value pairs ④ Key and Value can be any type of data (key cannot be a dictionary) ⑥ Key cannot be repeated , repetition will overwrite the original data

Syntax:
Define dictionary variables:
my_dict={key:value,key:value,…,key:value}
2 ways to define an empty dictionary:
①my_dict={}
②my_dict=dict()

Example:

# 定义字典
my_dict1 = {
    
    "二狗": 99, "小胖": 88, "大白": 77}
# 定义空字典
my_dict2 = {
    
    }
my_dict3 = dict()
print(f"字典1的内容是:{
      
      my_dict1},类型:{
      
      type(my_dict1)}")
print(f"字典2的内容是:{
      
      my_dict2},类型:{
      
      type(my_dict2)}")
print(f"字典3的内容是:{
      
      my_dict3},类型:{
      
      type(my_dict3)}")

# 定义重复key的字典
my_dict1 = {
    
    "二狗": 99, "二狗": 88, "大白": 77}
print(f"重复key的字典内容是:{
      
      my_dict1}")  # 字典不允许重复,新的会覆盖旧的,所以会保留最后一个

operation result:

The content of dictionary 1 is: {'Ergou': 99, 'Xiao Pang': 88, 'Dabai': 77}, type: <class 'dict'> The content of dictionary 2 is: {}, type: <class
' dict'>
The content of dictionary 3 is: {}, type: <class 'dict'>The
dictionary content of repeated key is: {'Ergou': 88, 'Dabai': 77}

Obtaining dictionary data

Dictionaries are like collections,Can'tUse subscript indexing
but dictionaries can be accessed viaKey value to get the corresponding Value

Nesting of dictionaries

The Key and Value of the dictionary can be any data type (Key cannot be a dictionary)
. This means that dictionaries can be nested .

Get the content of nested dictionary

Example:

# 从字典中基于key获取value
my_dict1 = {
    
    "二狗": 99, "小胖": 88, "大白": 77}
score = my_dict1["二狗"]
print(f"二狗的分数是:{
      
      score}")

# 字典的嵌套
stu_score_dict = {
    
    
    "二狗": {
    
    "语文": 99,
             "数学": 88,
             "英语": 77},
    "小胖": {
    
    "语文": 90,
             "数学": 80,
             "英语": 70},
    "大白": {
    
    "语文": 95,
             "数学": 85,
             "英语": 75},
}
print(f"学生的考试信息是:{
      
      stu_score_dict}")
# 从嵌套字典中获取数据
# 看一下二狗的数学成绩
score = stu_score_dict["二狗"]["数学"]
print(f"二狗的数学成绩是:{
      
      score}")

operation result:

Ergou's score is: 99.
The student's test information is: {'Ergou': {'Chinese': 99, 'Math': 88, 'English': 77}, 'Xiao Pang': {'Chinese': 90 , 'Math': 80, 'English': 70}, 'Dabai': {'Chinese': 95, 'Math': 85, 'English': 75}} Ergou's math score is:
88

Notes on Dictionaries

The Key and Value of a key-value pair can be of any type (Key cannot be a dictionary). Keys are not allowed to be repeated
in the dictionary . Repeated additions are equivalent to overwriting the original data. Dictionaries cannot be indexed with subscripts , but the Value is retrieved through the Key.

Common operations on dictionaries

Add new element

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

Note: The syntax of new and updated elements is the same. If the Key does not exist, it will be added . If the Key exists, it will be updated (the Key cannot be repeated) .

update element

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 an existing Key is to update the Value.

Delete element

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 deleted.

Clear dictionary

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

Get all keys

Syntax: dictionary.keys(), result: get all the keys in the dictionary

Traverse dictionary

Syntax: for key in dictionary.keys()

NOTE: Dictionaries do not support subscript indexing, so the sameCannot use while loopTraverse

Count the number of all elements (key-value pairs) in the dictionary

Syntax: len (dictionary)

Result: Get an integer representing the number of elements (key-value pairs) in the dictionary

Example:

# 定义一个字典
my_dict = {
    
    "ergou": 99, "dabai": 88, "xiaopang": 77}

# 新增元素
my_dict["erpang"] = 66
print(f"增加元素后:{
      
      my_dict}")
# 更新元素
my_dict["ergou"] = 55
print(f"更新元素后:{
      
      my_dict}")
# 删除元素
score = my_dict.pop("xiaopang")
print(f"字典删除一个元素后:{
      
      my_dict},xiaopang的分数是{
      
      score}")
# 清空元素,clear
my_dict.clear()
print(f"字典被清空了,内容是:{
      
      my_dict}")

# 获取全部的key
my_dict = {
    
    "ergou": 99, "dabai": 88, "xiaopang": 77}
keys = my_dict.keys()
print(f"字典的全部keys是:{
      
      keys}")

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

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

# 统计字典内的元素数量,len()函数
num = len(my_dict)
print(f"字典的元素数量有:{
      
      num}")

operation result:

After adding elements: {'ergou': 99, 'dabai': 88, 'xiaopang': 77, 'erpang': 66} After updating
elements: {'ergou': 55, 'dabai': 88, 'xiaopang': 77, 'erpang': 66}
After deleting an element from the dictionary: {'ergou': 55, 'dabai': 88, 'erpang': 66}, the score of xiaopang is 77. The dictionary is cleared, and the content is:
{}
dictionary All keys of the dictionary are: dict_keys(['ergou', 'dabai', 'xiaopang']). The
keys of the dictionary are: ergou.
The values ​​of the dictionary are: 99.
The values ​​of the dictionary are: dabai.
The values ​​of the dictionary are: 88.
The keys of the dictionary are: The value of the xiaopang
dictionary is: 77
2 The keys of the dictionary are: ergou
2 The value of the dictionary is: 99
2 The keys of the dictionary are: dabai
2 The value of the dictionary is: 88
2 The keys of the dictionary are: xiaopang
2 The value of the dictionary is: 77
dictionary The number of elements is: 3

Summary of common dictionary operations

serial number operate illustrate
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

Dictionary Features

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 Key:Value pair
4. Can be obtained through Key to Value , Key cannot be repeated (repetition will overwrite)
5. Subscript index is not supported
6. Can be modified ( adding or deleting updated elements, etc.)
7. Supports for loop, but does not support while loop

Dictionary usage exercises: promotion and salary increase

Guess you like

Origin blog.csdn.net/weixin_44996886/article/details/132678473