字典(Dictionary)
字典是一个无序、可变和有索引的集合。在 Python 中,字典用花括号编写,拥有键和值。
1,创建字典
dict_student = {‘name’:‘xiaoming’,‘age’:‘11’,‘hobby’:‘basketball’}
print(‘小学生小明:’, dict_student)
#小学生小明: {‘name’: ‘xiaoming’, ‘age’: ‘11’, ‘hobby’: ‘basketball’}
2,访问字典
dict_lover = {‘name’:‘ziyi’, ‘age’:‘20’, ‘hobby’:‘reading’ }
print(‘做梦才会遇到的人:’, dict_lover)
#做梦才会遇到的人: {‘name’: ‘ziyi’, ‘age’: ‘20’, ‘hobby’: ‘reading’}
young = dict_lover.get(‘age’)
print(‘她的芳龄是:’, young)
#她的芳龄是: 20
3,修改字典的值
dict_toy = {‘number’:‘1’, ‘call’:‘tydi bear’, ‘price’:‘99RMB’}
dict_toy[‘price’] = ‘999RMB’
print(‘玩具涨价了:’, dict_toy)
#玩具涨价了: {‘number’: ‘1’, ‘call’: ‘tydi bear’, ‘price’: ‘999RMB’}