文章目录
一、先看一个用字典的典型例子
1.统计字符串中所有字符出现的次数
"""
学习字典
统计字符串中所有字符出现的次数
"""
# txt = input("输入要统计的单词,回车结束\n")
txt= "泡芙 云南鲜花饼 泡芙 蛋黄酥 莲蓉蛋黄酥 奶黄流沙包 蛋黄酥 泡芙 辛拉面 牛排 魔芋爽 云南鲜花饼 云南鲜花饼"
words= txt.split(" ")
cnt_dict= {}
for word in words:
if cnt_dict.get(word) is None:
cnt_dict[word]= 1 #说明第一次出现
else:
cnt_dict[word]+= 1
print(cnt_dict)
output:
{'泡芙': 3, '云南鲜花饼': 3, '蛋黄酥': 2, '莲蓉蛋黄酥': 1, '奶黄流沙包': 1, '辛拉面': 1, '牛排': 1, '魔芋爽': 1}
涉及到的知识
cnt_dict.get(word):
get() 方法其实就是根据 key 来获取 value,它相当于方括号语法的增强版,当使用方括号语法访问并不存在的 key 时,字典会引发 KeyError 错误;但如果使用 get() 方法访问不存在的 key,该方法会简单地返回 None,不会导致错误。
二、字典
关键点:key-value对。
http://c.biancheng.net/view/2212.html 这个blog写的很好。
1.创建
1.1 dict[name]= value方式
student= { }
student['chen']= 18
student['jia']= 22
student['lin']= 24
output: {'chen': 18, 'jia': 22, 'lin': 24}
1.2 用dict()函数转为字典,只要元素和元素之间存在对应关系
#这个copy的别人的
vegetables = [('celery', 1.58), ('brocoli', 1.29), ('lettuce', 2.19)]
# 创建包含3组key-value对的字典
dict3 = dict(vegetables)
print(dict3) # {'celery': 1.58, 'brocoli': 1.29, 'lettuce': 2.19}
cars = [['BMW', 8.5], ['BENS', 8.3], ['AUDI', 7.9]]
# 创建包含3组key-value对的字典
dict4 = dict(cars)
print(dict4) # {'BMW': 8.5, 'BENS': 8.3, 'AUDI': 7.9}
1.3 dict(zip())法
name=['chen','jia','lin']
age=[18,22,24]
student= dict(zip(name,age))
output:{'chen': 18, 'jia': 22, 'lin': 24}
2、字典基本操作
待续。。。。
程序对字典的操作都是基于 key 的。基本操作如下
2.1 通过 key 访问 value
#法一
score = {'语文':90, '数学':80}
score['语文'] #90
score['物理'] #报KeyErro错误
#法二:get()方法
如果该key在字典里面,则返回对应的value;
如果该key不在字典里面,则会返回None
score.get('语文')# 90
score.get('物理')# None
注意:get()方法。常这样用:
if score.get()
courselist= ['语文','数学','英语','地理','历史']
for course in courselist:
if score.get(course) != None #没出现过
...
else:
... #出现过,做些处理
2.2 通过 key 添加 key-value 对
score['英语'] = 83
print(score)#{'语文':90, '数学':80, '英语':83}
2.3 通过 key 删除 key-value 对
del score['英语']
2.4 通过 key 修改 key-value 对
score['语文'] = 100#如果存在就修改掉,不存在则会添加为新的
print(score)#{'语文':90, '数学':80}
2.5 通过 key 判断指定 key-value 对是否存在
对于dict来说,in或者not in都是基于key来判断的。
print('物理' in score)#False
print('物理' in score)#True
2.6 一些方法
dir(dict)#['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
2.6.1 get()
上面讲了。
2.6.2 items()、keys()、values()
- items():获取字典中的所有 key-value 对
- keys():所有 key
- values() :所有 value
3、遍历
for key, val in student_dict.items():
print (key)
print (val)
三、二维字典例子
统计每个student存储的文档、视频、图片数量
filename内文档内容:
2020001 传闻中的陈芊芊.mp4
2020001 ┗|`O′|┛ 嗷~~.mp4
2020002 我最美.jpg
2020002 可爱的我.jpg
2020001 oh,买它.mkv
…
def stat_count(filename):
"""
统计
"""
document= ['txt','pdf','doc','docx','wps']
video= ['mkv','mp4','rmvb','rm','avi','AVI','wmv','mov']
image= ['BMP','JPG','JPEG','PNG','GIF','bmp','jpg','jpeg','png','gif']
has_label_suffix_set = document + video + image
uid_freq_dict = {}
f = open(filename, encoding='utf8')
# cnt = 0
for line in f:
line = line.strip()
fs = line.split('\t')
uid = fs[0]
file_names_suffix = fs[1].strip().split('.')[-1]
# print ( uid + '\t' + file_names_suffix )
if( file_names_suffix in document ):
key = 'document'
if( file_names_suffix in video ):
key = 'video'
if( file_names_suffix in image ):
key = 'image'
if( file_names_suffix not in has_label_suffix_set ):
key = 'others'
if( uid not in uid_freq_dict ):
uid_freq_dict[uid] = {}
if( key in uid_freq_dict[uid] ):
uid_freq_dict[uid][key] += 1
else:
uid_freq_dict[uid][key] = 1
# cnt += 1
# if( cnt > 40 ): break
f.close()
return uid_freq_dict
输出uid_freq_dict,是一个二维dict:
{'2020001':{'video': 45, 'others': 4},
'20200002':{'document': 1, 'image': 5},
'20200003':{'document': 2},
...
}