01.03 笔记-字典的操作

2019-01-03  本文已影响0人  xxxQinli

字典元素的增删改查

查(获取值)


car = {'color': '黄色', 'type': '跑车', 'price': '500000'}

print(car['color'])

print(car['price'])

\# print(car['speed']) \# KeyError: 'speed'


print(car.get('type'))

print(car.get('speed')) \# None

print(car.get('color', '红色'))

print(car.get('speed', 0))


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)

增、改

movie = {'name': '喜羊羊与灰太狼', 'type': '卡通', 'time': 120}

# 添加

movie['score'] = 7.9

print(movie)

# 修改

movie['type'] = '搞笑'

print(movie)

删(删除键值对)

del movie['time']

print(movie)

name = movie.pop('name')

print(movie, name)

itemtype = movie.popitem() \#弹出最后一个

print(movie, itemtype)
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)
上一篇下一篇

猜你喜欢

热点阅读