Python中字典的操作

时间:2022-12-18 12:19:15
1、字典key-value,key是不能重复的
stu_info={"name":"王志华","age":18,"addr":"北京"}
2、取值,查
print(stu_info['name'])
print(stu_info['age'])
print(stu_info['addr'])
# print(stu_info['we']) #取不存在的key的值,会报key不存在的错误
#.get方法取值
print(stu_info.get('name'))
print(stu_info.get('we')) #取不存在的key的值,会返回None,取值最好用.get方法,不会报错
print(stu_info.get('login',500)) #如果值不存在,就返回逗号后面的值,这个返回500

2、修改
stu_info['addr']='上海'
print(stu_info)

3、新增
stu_info['phone']=123456
stu_info.setdefault('email','zyq@163.com')
print(stu_info)
#新增一个不存在的key,不会修改value的值
stu_info.setdefault('age','19')
print(stu_info)

4、删除
stu_info.pop('email')
print(stu_info)
del stu_info['age']
print(stu_info)

# stu_info.popitem() #从字典中随机删除一个元素
# stu_info.clear() #清空字典
stu_info['age']=20
print(stu_info)
5、把一个字典加到另外一个字典里
d1={'b':1}
d2={'a':2}
d1.update(d2)#把d2加到d1中
print(d1)
6、循环字典
print(stu_info.keys())#打印所有的key
print(stu_info.values()) #打印所有的values
#直接循环字典,打印出来都是字典中的key
for i in stu_info:
print(i)
#判断key是否存在
print('name'in stu_info.keys())
print('name' in stu_info)

#第一种,这种效率比第二种效率高
第一种,取key和value的值:
for i in stu_info:
s='%s=>%s'%(i,stu_info.get(i))
print(s)
#第二种
for k,v in stu_info.items():
print('%s=>%s'%(k,v))

print(stu_info.items())

7、字典的嵌套
#字典嵌套
stu_info={
'xiaoming':{"password":123456,"phone":1323214,"age":18,"addr":"北京"},
"xiaohei":{"password": 123456,"phone": 132321,"age": 18,"addr": "上海"}
}
print(stu_info['xiaoming']['phone'])
d = {
'春波':{
"car":{'BMW':5,'BENZ':3,'audi':3,'byd':4},
"house":["北京",'南京','上海'],
"money":1000000,},
'乔美玲':{
"bag":['xx','lv',],
"house":['三环','4环'],
"hzp":['skii','ysl'],
'language':{
'普通话':10,
'东北话':20,
'日语':0,
'英语':4
}
}
}

#1、马春波卖了一套上海的房子,买了500百万
d['春波']['house'].pop(-1)
print(d['春波']['house'])

d['春波']['money']+=5000000
print(d['春波']['money'])
#2、算一下马春波有多少辆车
car_num=d['春波']['car'].values()
print(sum(car_num))
#3、春波花了100百万买了一辆莱斯莱斯
d['春波']['money']-=1000000
print(d['春波']['money'])

d['春波']['car'].setdefault('莱斯莱斯',1)
print(d['春波']['car'])
#4、乔美玲的东北话从20级变成了10级
d['乔美玲']['language']['东北话']-=10
print(d['乔美玲']['language']['东北话'])
#5、乔美玲会哪几种语言
for k in d['乔美玲']['language']:
print(k)