2018.09.18python学习第六天part2

4.dict
# 用{}记录多个key:value的值,用逗号分隔开
# value可以是任意类型的值,key一定要是不可变类型,且要对value具有说明性

#1.按key取值
# dic={0:'aaa',1:'bbb',2:'cccc'}
# print(dic[1])#这是取值
# dic[1]="BBB"
# print(dic)#说明dict类型是可变的
# dic[3]="ddd"
# print(dic)#和list的不同,可以添加原来dict没有的值
#
# 2.len
# dic={0:'aaa',1:'bbb',2:'cccc'}
# print(len(dic))#这个是key的长度

# 3.in or not in
# dic={0:'aaa',1:'bbb',2:'cccc'}
# print("aaa" in dic)#False
# print(1 in dic)#True
# 所以dict的成员运算是是key in or not in dict

# 4.删除
#del
# dic={0:'aaa',1:'bbb',2:'cccc'}
# del dic[1]
# print(dic)#单纯的删除,没有返回值
# del dic[3]
# print(dic)#删除没有的值是则会报错

#pop
# dic={0:'aaa',1:'bbb',2:'cccc'}
# dic.pop(1)
# print(dic)#具有返回值
# print(dic.pop(0))#返回值为key对应的value

# popitem #随机删除
# dic={0:'aaa',1:'bbb',2:'cccc'}
# res=dic.popitem()
# print(dic)
# print(res)

# 5、键keys(),值values(),键值对items()
# dic={0:'aaa',1:'bbb',2:'cccc'}
# print(dic.values())#取dict的valuer
# print(dic.keys())#取dict的key
# print(dic.items())#取出来后是一个元组

# l=[]
# for k in dic.values():
# l.append(k)
# print(l)#用for循环取值并做成一个list

# print(list(dic.values()))#直接用list数据类型转换功能转成list

# 6.循环
# dic={0:'aaa',1:'bbb',2:'cccc'}
# for k in dic.keys():
# print(k,dic[k])
# for k,v in dic.items():
# print(k,v)

# 7.get
# dic={0:'aaa',1:'bbb',2:'cccc'}
# print(dic.get(2))
# print(dic.get(4)#当取dict中没有的值时,不会报错,但是显示为None

# 8.setdefault#修改:能找到就不修改,找不到就添加
# dic={0:'aaa',1:'bbb',2:'cccc'}
# res=dic.setdefault(1,"BBB")
# print(dic)
# print(res)
#
# res1=dic.setdefault(4,"DDD")
# print(res1)#找不到4的key,所以就添加了4:"DDD"的值
# print(dic)#找不到4的key,所以就添加了4:"DDD"的值

# 9.fromkeys
# l=['name','age','sex']
# dic={'name':None,'age':None,'sex':None}
# dic=dict.fromkeys(l,None)
# print(dic)

# dict类型总结
# 1.多个值
# 2.无序
# 3.可变(不可hash)

posted on 2018-09-18 20:04  撩与诗人  阅读(124)  评论(0编辑  收藏  举报