day5 字典

day5 字典
#字典
数据类型划分:可变数据类型,不可变数据类型
不可变数据类型:元祖,bool, int ,str 可哈希
可变数据类型:list,dict,set 不可哈希
dict key:必须是不可变数据类型,可哈希
value:任意数据类型
dict优点:二分查找法查询
储存大量关系型数据
特点:无序的
dic = {"name":["大猛","小猛"],
'py9':[{'num':71,'avg_age':18}],
True:1,
(1,2,3):'wupeiqi',
2:'二哥'}
print(dic)

dic1 = {'age': 18, 'name': 'jin', 'sex': 'male',}
#增:
dic1['high'] =185 #没有键值对,添加
dic1['age'] =16 #如果有键,则值覆盖
# dic1.setdefault('weight')
dic1.setdefault('weight',150)
dic1.setdefault('name',"haha")#有键值对,不做任何改变,没有才添加
print(dic1)

 

#删
dic1.pop("age")#有返回值,按键去删除
print(dic1.pop("二哥","没有此键"))#可设置返回值
print(dic1)

dic1.popitem() #随机删除,有返回值,元祖里面是删除的键值
print(dic1)

dic1.clear()#清空字典
print(dic1)

del dic1['name']#删除键值对
print(dic1)

#改 update
dic = {"name":"jin","age":18,"sex":"male"}
dic2 = {"name":"alex","weight":75}
dic2.update(dic) #update为覆盖添加

print(dic)
print(dic2)'''

dic1 = {'age': 18, 'name': 'jin', 'sex': 'male',}
#查
print(dic1.keys(),type(dic1.keys()))
print(dic1.values())
print(dic1.items())

for i in dic1:
print(i)
for i in dic1.keys():
print(i)

for i in dic1.values():
print(i)

a,b = 1,2
print(a,b)
#面试题:a,b = 1,2,用一行代码转换a,b的值
a=1
b=2
a,b=b,a
print(a,b)

a,b=[1,2]
c,d=[3,4]
print(a,b)
print(c,d)
for k,v in dic1.items():
print(k,v)
v1 = dic1['name']
print(v1)

v2 = dic1['name1']#报错
print(v2)


print(dic1.get("name1"))
print(dic1.get("name1","没有这个键"))

字典嵌套
dic = {
'name':['alex','wusir','taibai'],
'py9':{
'time':'1213',
'learn_money':19800,
'addr':'CBD',
},
'age':21
}

dic['age']=56
print(dic)
dic['name'].append("日天")
print(dic)

dic['name'][1]=dic['name'][1].upper()
print(dic)

posted @ 2019-03-03 22:40  Murraya  阅读(81)  评论(0编辑  收藏  举报