学习python -- 第008天 字典

字典

字典

字典的创建

 1 #
 2 # @author:浊浪
 3 # @time: 2021/3/13 15:33
 4 
 5 ''' 创建字典 '''
 6 # 两种方法
 7 '''直接使用{}创建'''
 8 score = {'zhangsan': 100, 'lisi': 80, 'wangwu': 60}
 9 print(score)
10 print(type(score))
11 
12 '''使用内置函数dict创建 注意key不需要加单引号'''
13 student = dict(aaa=45, bbb="sdsds")
14 print(student)
15 
16 '''创建空字典'''
17 d = {}
18 print(d)

字典元素的获取

 1 #
 2 # @author:浊浪
 3 # @time: 2021/3/13 15:42
 4 
 5 '''字典元素的获取的两种方法'''
 6 score = {'zhangsan': 100, 'lisi': 80, 'wangwu': 60}
 7 # '''第一种,使用[]'''
 8 print(score['zhangsan'])
 9 
10 # print(score['sad'])  #会报错  KeyError: 'sad'
11 
12 
13 # 第二种使用get()方法
14 print(score.get('zhangsan'))
15 print(score.get('sddsa'))  #不会报错,返回none

字典的操作

 

 1 #
 2 # @author:浊浪
 3 # @time: 2021/3/13 15:49
 4 
 5 score = {'zhangsan': 100, 'lisi': 80, 'wangwu': 60}
 6 print('zhangsan' in score)
 7 print('zhangsan' not in score)
 8 
 9 
10 del score['zhangsan']  #删除一个指定的key-value对
11 # score.clear()  #清空字典
12 print(score)
13 
14 score['sad'] = 99  #新增一个元素
15 print(score)
16 
17 score['sad'] = 98  #修改一个元素
18 print(score)
19 
20 
21 
22 '''获取字典视图'''
23 # 获取所有的key值
24 keys = score.keys()
25 print(keys, '
', type(keys))
26 print(list(keys))  #把所有的keys组成一个列表
27 
28 # 获取所有的value的值
29 value = score.values()
30 print(value, '
', type(value))
31 print(list(value))  #把所有的value组成一个列表
32 
33 # 获取所有的key-value对
34 items = score.items()  # 元组
35 print(items, '
', type(items))
36 print(list(items))  #把所有的items组成一个列表

字典的遍历

1 for i in score:
2     print(i, score[i], score.get(i))

字典的特点

字典生成式 

 1 #
 2 # @author:浊浪
 3 # @time: 2021/3/13 16:10
 4 
 5 item = ['fruits', 'books', 'other']
 6 price = [90, 67, 93, 78, 89]
 7 
 8 d = {item.upper():price for item, price in zip(item, price)}  #value多的时候会截取前面的
 9 print(d)
10 
11 
12 items = ['fruits', 'books', 'other', 'dfsd', 'fd']
13 prices = [90, 67, 93, 79]
14 d1 = {items.upper():prices for items, prices in zip(items, prices)}  #key多的时候会截取前面的
15 print(d1)
认清现实,放弃幻想。 细节决定成败,心态放好,认真学习与工作。
原文地址:https://www.cnblogs.com/jyf2018/p/14529289.html