字典创建(两种方法)
dic = {'word':12,'hello':10,'key':0} #1直接创建
dic = {} #2创建空字典
a = (('word',12),('hello',10))
dic = dict(a) ##3将元组改为dic
字典的增删改查
1,增加(两种方法)
dic['mother'] = 10 #1 -> 直接增加,若key存在则覆盖原key,value
dic.update({'mother':10}) #2 -> 利用update增加
2,删除(三种方法)
x = dic.pop('mother')
# 1 -> dic.pop(key) -> 返回value,同时删除(key,value)
# x -> 12
del dic['mother']
# 2 -> del dic[key] -> 没有返回值,直接删除
dic.clear()
# 3 -> dic.clear() ->调用dic封装的函数,清空dic
# 清空dic, dic={} dic在内存中还存在
# del dic 直接删除dic对象
3 ,更改(同增加操作,有key直接覆盖,没有增加,update也试用)
4,查找(常见的操作)
dic.items() # 以元组形式返回dic中的键值对
dic.keys() # 返回dic中的key
dic.values() # 返回dic中的values
dic.get(key,0) # 获取dic中key对应的value,若不存在该key, 返回 0
dic.setdefault(key,1) #获取dic中key对应的value,若不存在该key,则 创建 dic[key]= 1
注意1:dic.items()是作为一个可迭代对象返回的,不能用直接用x = dic.items()[0]这样的方式获取dic中的第一个(key,value),可以用下面这样的方式来获取。dic.keys(),dic.values()同理。
x = [x for x in dic.items()][0]
注意2::写 for i in dic时,i不会返回键值对,默认i返回的是key。等价于 for key in dic.keys()。
应用实例:词频统计
corpus = ['hello','dear','my','name','is','foo','my','father','name','is','fuu',\
'my','mother','name','is','lyy']
dic = {}
for word in corpus: ##统计频率
dic[word] = dic.get(word,0) + 1
dic_sort = sorted(dic.items(),key = lambda x:x[1],reverse = True) #排序->list
'''
# 上面内容等价于,只不过返回类型不同
dic = collections.Counter(corpus) '''
print(dic_sort[:5]) #输出频率最高的前5个的