字典元素的增删改查
查(获取值)
注意:字典中的键值对单独拎出来没有任何意义
a.字典[key] - 获取字典中key对应的值
car = {'color': '黄色', 'type': '跑车', 'price': '500000'}
print(car['color'])
print(car['price'])
\# print(car['speed']) \# KeyError: 'speed'
- b.字典.get(key) - 获取字典中key对应值
print(car.get('type'))
print(car.get('speed')) \# None
print(car.get('color', '红色'))
print(car.get('speed', 0))
-
c.遍历字典
-直接通过for in 遍历字典取到的是key
dict1 = {'a': 100, 'b': 200, 'c': 300}
for x in dict1:
print(x)
\# 获取values
for value in dict1.values():
print(value)
\# 获取keys
for key in dict1.keys():
print(key)
\# 获取键值对 不建议使用,性能不佳
for key, value in dict1.items():
print(key, value)
增、改
- a.字典[key] = 值 - 当key不存在的时候,添加键值对,当key存在的时候,就是修改key对应的值
movie = {'name': '喜羊羊与灰太狼', 'type': '卡通', 'time': 120}
# 添加
movie['score'] = 7.9
print(movie)
# 修改
movie['type'] = '搞笑'
print(movie)
删(删除键值对)
a.del 字典[key] - 删除字典中指定的键值对
b.字典.pop(key) - 取出字典中key对应的值,并删除这个键值对
del movie['time']
print(movie)
name = movie.pop('name')
print(movie, name)
itemtype = movie.popitem() \#弹出最后一个
print(movie, itemtype)
练习:用一个字典保存一个学生的信息:{'name': 'zhangsan', 'age': 30, 'score':80}
输入需要修改的信息,例如输入name -> 修改的名字, age -> 修改年龄...若不存在,提示不存在
zhangsanID = {'name': 'zhangsan', 'age': 30, 'score':80}
while True:
key = input('请输入要修改的关键字(name、age、score),输入end退出: ')
if key == 'end':
print('bye!')
break
elif key not in zhangsanID:
print('没有"%s"信息,请重新输入' % key)
print('-' \* 30)
continue
else:
value = input('请输入要修改的信息: ')
zhangsanID[key] = value
print('信息“%s”已修改为: %s' % (key, zhangsanID[key]))
for key, value in zhangsanID.items():
print('%s ---\> %s' % (key.ljust(5, ' '), str(value).ljust(5, ' ')))
print('-' \* 30)