Python字典学习
在Python中,列表和字典常用于存储数据。
日常生活中,经常会去买饮料。饮料有果汁、咖啡、奶茶等,各自又分大、中、小杯,这时就用上了字典。
(1)字典的创建,键值对的添加、修改和删除
一个简单的字典:
drink={'type':'juice','number':2,'size':'medium'}
添加键值对:
drink['temperature']='normal'
修改值:
drink['type']='tea'
删除键值对:
del drink['size']
(2)遍历字典
遍历键值对:
for key, value in drink.items():
print('key: '+key)
print('value : '+str(value) )
遍历键:
for key in drink.keys():
print(key)
按顺序遍历键:
for key in sorted(drink()):
print(key)
遍历值:
for v in drink.values():
print(v)
剔除重复值:
for v in set(drink.values()):
print(v)
(3)嵌套
列表嵌套字典:
drink_1={'type':'juice','number':2,'size':'medium'}
drink_2={'type':'coffee','number':3,'size':'medium'}
drink_3={'type':'tea','number':5,'size':'medium'}
drinks=[drink_1,drink_2,drink_3]
for drink in drinks:
print(drink)
字典嵌套列表:
drink={'type':'juice','number':2,'size':'medium','others':['sugar', 'pearl']}
for k,v in drink.items():
print('key: '+k)
print('value: '+str(v))
字典嵌套字典:
drink={'type':'juice',
'number':2,
'size':'medium',
'others':{'sugar':'normal'}
}
for v in drink.values():
print(v)
总结:
今天回顾了字典的基本操作,重新认识了items()、keys()、values()三个方法,还有set()集合。需要注意标点等细节。