Python (3.9.7) dictionary (comprehensive, detailed)

        Current python version: 3.9.7 The software is pycharm professional version, the following codes and screenshots are all from running under pycharm software

Learning Catalog:

Uses of dictionaries:

Advantages of dictionaries:

Features of dictionaries

How to write a dictionary:

Dictionary additions:

Increase:

Checked increase (setdefault):

 Dictionary deletion:

1. Delete (pop):

2. Delete (del can be used globally)

 3. Delete (poitem):

4. Clear

 Changes to the dictionary:

1. Common modification

2. Merge and modify

Dictionary lookup:

1. Check (get):

 2. Ordinary query method (different from get)

dictionary comprehension

Regarding the length of the dictionary:

Determine whether there is a key value in the dictionary

 On the circular writing of dictionaries

Special usage of dictionaries:

Batch generation dictionary method:

 copy copy is shallow copy like list

 Small exercise (combining multiple lists into a dictionary)


Uses of dictionaries:

        When your list has a large amount of data, when you loop the list, the speed is slow and it takes up resources. Now we can use the dictionary that comes with python

Advantages of dictionaries:

        The query speed is fast, the operation is convenient, and the query speed will not slow down due to the increase in the amount of data

Features of dictionaries

1. key: value structure

2. The key must be an immutable data type (character conversion, number, tuple) that cannot be modified to be called the key value

3. The key must be a unique value (non-repeatable) (repetitive ones will overwrite long-term ones)

4. The value corresponding to a key can store any data type, which can be modified and not unique

5. Can be nested, that is, the value value can also be a dictionary (can be nested list)

6. It was unordered before pyhon3.7 (you can use ordered_dict if you want to have an order), and it becomes ordered after 3.7

7. The query speed is fast and not affected by the size of the dictionary

How to write a dictionary:

普通写法:

staff_list ={
    "maliu":[22,"CEO",200000] #前面这个"maliu"就是字典中的key值(索引),可以通过这个去查找内容
    "zhangsan":[23,"财务",6000]
    #..........
    
}

dict写法:

a = dict(name='gaoxidong', age=22)

列表式写法:

c = {'ziwojieshao': ['gaoxidong', 22, 'man']}

 "name": [22,'CEO','20000'] ##"name" is the key value, and the value of "value" is: [22,'CEO','20000'] 

The key value is similar to the radicals in the Xinhua dictionary we use, and you can quickly query the content through the keyword eye

Dictionary additions:

Increase:

Precautions:

#If repeated, the original value will be overwritten (when you repeatedly add a key value, it can play a role in modifying the value, remember that the key value is fixed and cannot be modified), but it is easy to change the original dictionary by mistake Lose

a = dict(a='xiaoming')
a['b'] = 'zhangsan'  #增
a['c'] = ['wangwu', 23, 4000] #key不可重复
print(a) #显示当前
print(a['b'])  #查询字典对应key的value值

 operation result:

Checked increase (setdefault):

Precautions:

#In order to avoid overwriting the original value, then we use the check method to add. The advantage of this method is that it will judge whether the key value you added is in the dictionary. If it is not, it will be added. If it exists, it will display the original value. The value value!

Writing:

a = dict(name='gaoxidong')

print(a.setdefault('name', 'jack')) #如果key值存在,则返回旧key的value值(如果key:value重复的情况,不会修改原有的)

b = {
    'age':23
}

print(b.setdefault('name','gaoxidong'))#创建并返回value值(增)#默认在最后添加

print(a, b) #打印a,b两个字典

operation result:

 Dictionary deletion:

1. Delete (pop):


Writing:

a = dict(gaoxidong=[23, '运维', 6000],
         zhangsan=[26, '运维', 8000],
         )
print(a.pop('gaoxidong')) #删除key值,并返回删除key值的value值

print(a) #删除后打印字典a

a.pop('zhangsan01') #如果key值不存在 会报错

operation result:

2. Delete (del can be used globally)
 

Writing:

a = dict(gaoxidong=[23, '运维', 6000],
         zhangsan=[26, '运维', 8000],
         )

del a['gaoxidong']  #这种删除并不会返回被删除的key值  #在pycharm中这里地方是无法加print的 ##错误写法 print(del a['gaoxidong']) 

print(a)

operation result:

 3. Delete (poitem):

Precautions:

 #Delete a pair of values ​​in a LIFO way

##LIFO means that deleting from the last key value is randomly deleted before py3.7 (because the dictionary sorting is out of order before version 3.7)

#Note poitem()#The value cannot be filled in the parentheses, and the fixed key value cannot be deleted

Writing:

a = dict(gaoxidong=[23, '运维', 6000],
         zhangsan=[26, '运维', 8000],
         )

print(a.popitem())  #打印删除的值 #括号内无法填写值
print(a) #打印删除后的结果

operation result:

Deleted the last line dictionary 

4. Clear

Precautions:

If you use clear to clear, all your corresponding dictionaries will be cleared

b = {
    'zhangsan': [30, '开发', 12000],
    'lisi': [26, '运维', 8000]
}
print(b.clear())  #这里注意如果你打印的话,返回的是None的值 也就是空,但是效果还是会执行的

print(b)  #打印执行结果

operation result:

 Changes to the dictionary:

1. Common modification

Writing:


a = dict(gaoxidong=[23, '运维', 6000],
         zhangsan=[26, '运维', 8000],
         )
a["gaoxidong"][1] = "开发"  #将字典“gaoxidong”对应的value值修改(修改列表)
a["gaoxidong"][2] = "10000" 

print(a) 

operation result:

2. Merge and modify

Precautions:

#Update b dictionary to a dictionary, if there is a duplicate key value of b dictionary in a dictionary, then the value of b dictionary will overwrite the value of a dictionary

#定义列表a
a = dict(gaoxidong=[23, '运维', 6000], 
         zhangsan=[26, '运维', 8000],
         )
#定义列表b
b = {
    'zhangsan': [30, '开发', 12000],
    'lisi': [26, '运维', 8000]
}

#将b字典更新到a字典,如果a字典中有b字典的重复key值,那么b字典的value值会覆盖a字典的value值
a.update(b)  #将b字典更新到a字典当中
print(a)

operation result:

Dictionary lookup:

1. Check (get):

Precautions:

Get query method, if the query key value does not exist, no error will be reported, only None will be displayed

a = dict(gaoxidong=[23, '运维', 6000],
         zhangsan=[26, '运维', 8000],
         )
print(a.get('gaoxidong')) #如果key值存在 则返回value值
print(a.get('gaoxidong01')) #如果key值不存在,不会报错,但是会返回None(为空)
#如果在python中直接写a.get('gaoxidong01')则不会报错 不加print也看不到返回的'None'

operation result:

 2. Ordinary query method (different from get)

Precautions:

This is different from the get method. This method will query without reporting an error. Pay attention to the difference between the two

b = {
    'zhangsan': [30, '开发', 12000],
    'lisi': [26, '运维', 8000]
}
print(b['zhangsan'])  #存在则返回一个key值的value值
print(b['zhangsan01'])#不存在的key值则会直接报错
###运行结果
[30, '开发', 12000]
KeyError: 'zhangsan01'  #报错信息

operation result:

dictionary comprehension

 

a = "候鸡狗猪鼠牛虎兔龙蛇马羊"

b = {i:"test" for i in a}   #字典推导式与列表推导式是非常相似的,不过字典推导式key值不能重复
print(b)

 operation result:

 

Regarding the length of the dictionary:

Precautions:

 #key and value are one, so the length is the number of keys that return results according to the key value, and the length is how many

Writing:

a = dict(gaoxidong=[23, '运维', 6000],
         zhangsan=[26, '运维', 8000],
         )
print(len(a)) #len()方法同时用于字符串与列表 字典也是可以的 
#key与value是一个 所以长度也就是按key值来返回结果的 几个key 长度就是几个

 operation result:

 

Determine whether there is a key value in the dictionary

Method: in

Writing:

b = {
    'zhangsan': [30, '开发', 12000],
    'lisi': [26, '运维', 8000]
}
print('zhangsan' in b)  #如果key值zhangsan在字典内则返回 True
print('zhangsan01' in b)#如果不在则返回 False

operation result:

 On the circular writing of dictionaries

Precautions:

When you want to display the list contained in the corresponding value individually, it cannot be written as b.values()[1], it can only be used for loops to obtain a single value 

The values ​​queried in this way are in the form of tuples

Writing:

#定义列表
b = {
    'zhangsan': [30, '开发', 12000],
    'lisi': [26, '运维', 8000]
}
###显示全部key值
print(b.keys())  
#循环写法 
#for i in b.keys(): #values同理
#    print(i)
###显示全部value值
print(b.values()) #这里注意没办法当成列表使用 ##错误示范 b.values()[0] #这样写是错误的
###只能用于循环来单个取值!!!

operation result:

 The above writing method is not efficient, we can convert it to the form of tuple:

It is obvious from the following that after converting to a tuple, it is more convenient for us to extract the key and value inside


b = {
    'zhangsan': [30, '开发', 12000],
    'lisi': [26, '运维', 8000]
}

print(b.items()) #将字典转换为元组
for k,v in b.items(): #将key值vlaue值分别赋值给k,v
    print(k)
    print(v)

operation result:

 

Special usage of dictionaries:

Batch generation dictionary method:

Writing:

#批量生成字典formkeys(生成多个key与value值)
a = ['gaoxidong', 'zhangsan', 'wangwu']  # 首先定义一个列表
b = dict.fromkeys(a)  # 注意不给默认值的话 字典结果为None(空)
print(b)
c = dict.fromkeys(a, 'test')  # 加一个默认值,但是注意后面加的默认值是固定的
print(c)

operation result:

 copy copy is shallow copy like list

Precautions:

A shallow copy is almost like a broken root. There are codes and explanations below, so you can try it yourself.

Writing:

b = {
    'zhangsan': [30, '开发', 12000],
    'lisi': [26, '运维', 8000]
}
c = b.copy()
print(b)
c['zhangsan'][2] = 14000 #如果c的value值修改了,那么b的也会跟着一块变  #这就是浅copy 
print(c,b)

operation result:

 Small exercise (combining multiple lists into a dictionary)

Requirement: Generate a dictionary of hundreds of people, and each value cannot be the same

Writing:

import random,faker  #没有faker 请用 pip install faker下载,#faker是人名库
#random 随机取值模块
a = []
name = faker.Faker(locale="zh_CN")  #设置中文

for i in range(1, 101):  #我们批量创建100个字典
    # suiji = random.randint(1, 30)
    a.append(f"{name.name()}") #先将内容加入到列表中
print(a)
###列表推导式方法 a = [f"{name.name()}"for i in range(1,101)]
b = []  #定义空列表
for s in range(1, len(a) + 1):  #我们根据a例表的长度 +1,因为从1开始的 但不包括1 所以+1
    age = random.randint(18, 35)
    RMB = random.randint(3000, 10000)
    b.append([f"员工号:{s}", f"年龄:{age}", RMB]) #将内容加入到列表b中
c = dict(zip(a,b))     #将a列表与b列表结合,并且a列表的值当key值,b列表当value值
print(c)

operation result:

 

 

Guess you like

Origin blog.csdn.net/weixin_58279299/article/details/125094622