字典及其内置方法
不可变类型=》可hash类型:id 不变,无法修改值
可变类型 =》不可以hash类型:id不变,可以修改值
一:基本使用dict
1 用途:记录多个值,每一个值都对应的key用来描述value的作用
2 定义方式:在{}内用逗号分隔开多 个key:value,其中value可以是任意类型,而key必须是不可变的类型,通常情况下应该str类型
dic={0:'aaa',1:'bbb',2:'cccc'}
print(dic,type(dic))
用法一:
dic=dict(x=1,y=2,z=3)
print(dic)
用法二:
userinfo=[
['name','egon'],
['age',18],
['sex','male']
]
d={}
for k,v in userinfo: #k,v=['name', 'egon']
#print(k,v)
d[k]=v
print(d)
d=dict(userinfo)
print(d)
3 常用操作+内置的方法
优先掌握的操作:
#1、按key存取值:可存可取
# 注:key具有唯一性(重复会覆盖旧值),value可以重复
dic = {1: None, None: None, 3.14: None,True: None, 'abc': None, (1,): None,None: 12345}
print(dic)
#2、长度len
dic={'name':'egon','age':18,'name':'EGON','name':'XXXX'}
print(dic)
print(len(dic))
# 字典无序存储数据,无索引与切片,用key来取值
#3、成员运算in和not in:字典的成员运算判断的是key
dic={'name':'egon','age':18,}
print(18 in dic)
print('age' in dic)
#4、删除
dic={'name':'egon','age':18,}
# 通用
del dic['name']
print(dic)
del dic['xxx'] ##key不存在则报错
res=dic.pop('age') #删除key及其对应的value,并返回value
print(dic)
print(res) #
dic.pop('xxx') #key不存在则报错
res=dic.popitem()
print(dic)
print(res)
#5、键keys(),值values(),键值对items()
dic={'name':'egon','age':18,}
print(dic.keys())
l=[]
for k in dic.keys():
l.append(k)
print(l)
print(list(dic.keys()))
print(dic.values())
print(list(dic.values()))
print(dic.items())
print(list(dic.items()))
#6、循环
dic={'name':'egon','age':18,'sex':'male'}
# for k in dic.keys():
# print(k,dic[k])
# for k in dic:
# print(k,dic[k])
# for v in dic.values():
# print(v)
# for k,v in dic.items():
# print(k,v)
#8 dic.get()
dic={'name':'egon','age':18,'sex':'male'}
# dic['xxx']
# v=dic.get('name')
# print(v)
# v=dic.get('xxx')
# print(v)
需要掌握的操作:
# dic.fromkeys()的用法:
# l=['name','age','sex']
# dic={'name':None,'age':None,'sex':None}
# dic={}
# for k in l:
# dic[k]=None
# print(dic)
# dic=dic.fromkeys(l,None)
# print(dic)
# old_dic={'name':'egon','age':18,'sex':'male'}
# new_dic={'name':'EGON','x':1,'y':2}
# old_dic.update(new_dic)
# print(old_dic)
# setdefault:有则不动/返回原值,无则添加/返回新值
# dic={'name':'egon','age':18}
# res=dic.setdefault('name','EGON') # 字典中已经存在key则不修改,返回已经存在的key对应的value
# print(dic)
# print(res)
# res=dic.setdefault('sex','male') # 字典不存在key则添加"sex":"male",返回新的value
# print(dic)
# print(res)
练习一
# 独自设置默认值
d11 = {'a': 10, 'teas': ['Owen']}
# 添加老师
# 如果有teas,在原teas基础上添加老师,如果没有,新建一个空teas
# if 'teas' not in d11: # 成员运算
# d11['teas'] = []
# d11['teas'].append('Egon')
# d11['teas'].append('LiuXX')
# print(d11)
# 原d11中,如果有teas这个key,setdefault相当于什么都没干
# 如果没有,就将第二个参数(默认值)传给teas存放到d11中
d11.setdefault('teas', [])
d11['teas'].append('Egon')
d11['teas'].append('LiuXX')
print(d11)
练习二
# nums=[11,22,33,44,55,66,77,88,99,90]
# dic={
# 'k1':[],
# 'k2':[]
# }
# for num in nums:
# if num > 66:
# dic['k1'].append(num)
# else:
# dic['k2'].append(num)
# print(dic)
#
练习三
# s='hello alex alex say hello sb sb'
# words=s.split()
# dic={}
# # print(words)
# for word in words:
# if word in dic:
# dic[word]+=1
# else:
# dic[word]=1
#
# print(dic)
# s='hello alex alex say hello sb sb'
# words=s.split()
# dic={}
# for word in words: # word="hello"
# dic.setdefault(word,words.count(word)) #{'hello':2,"alex":2,"say":1,}
# print(dic)
该类型总结
1 存多个值
2 无序
3 可变
# dic={'x':1}
# print(id(dic))
# dic['x']=2
# print(id(dic))