字典
1.作用
对于值添加描述信息使用它
2.定义方式
用{}以逗号隔开加入键值对key:value
info_dict = {'name':'wangdapao','age':18,'height':120,'gender':'famale','hobby_list':['dapao','666']}
3.内置方法
优先掌握
1.按key取值,即可取也可以改变
print(info_dict['hobby_list']) #['dapao','666','233']
info_dict['age'] = 20
print(info_dict) #{'name':'wangdapao','age':20,'height':120,'gender':'famale','hobby_list':['dapao','666']}
2.长度len
print(len(info_dict)) #5
3. in/not in
print('name' in info_dict) #True
4.for循环
for i in info_dict:
print(i)
5.keys/values/items,items用的最多,)
print(list(info_dict.keys())) #list
print(list(info_dict.values())) #list
print(list(info_dict.items())) #list
for i in info_dict.values():
print(i)
info_dict = {'name':'wangdapao','age':20,'height':120,'gender':'famale','hobby_list':['dapao','666']}
print(info_dict.items())
for i in info_dict.items():
print(i)
for k,v in info_dict.items():
print(k,v)
lt = [[1,2,3],[2,3,4],[5,6,7]]
for a,b,c in lt:
print(a,b,c)
需要掌握
info_dict = {'name':'wangdapao','age':20,'height':120,'gender':'famale','hobby_list':['dapao','666']}
print(info_dict.copy())
info_dict.pop('name')
print(info_dict)
info_dict.popitem() #早起的时候是随机删除的,但是由于python3底层优化了字 print(info_dict) 典,让字典看的貌似有序了,所以默认删除最后一个
info_dict.clear()
print(info_dict)
(info_dict.get('age'))
#print(info_dict['name'])
print(info_dict.get('name','nick')) #如果有,就返回真正的值,如果没有,默 认返回None,也可以指定返回
if jiangpin_lan_dict.get(reward) is None: #None和小整数池一样固定不变的id
info_dict.setdefault('gender',123123) #有则不变,无则往里面追加了值
print(info_dict)
info_dict.update({'a':1})
print(info_dict)
4.存一个值还是多个值
多个值
5.有序or无序
无序
6. 可变or不可变(重点)
可变
dic = {'a':1}
print(id(dic))
dic['b'] = 1
print(id(dic))