整理是为了方便自己学习记忆使用。
参考书籍《Python编程--从入门到实践》(第2版),[美] 埃里克·玛瑟斯。
一、使用字典
字典是由键和值组成的,以成对的形式出现。
键:值
child = { 'age' : 5, 'color' : 'red' }
上述表达式,是字典的基本组成。其中age和color是键,5和red是值。键需要用单引号引起,当值为字符串的时候,也需要用单引号引起。
键和值之间用冒号分割,而键值对之间用逗号分割。
1、访问字典中的值
字典名[ '键' ]
child = {'age':5, 'color':'red'}
print(child['age'])
print(f"The child likes {child['color']}.")

2、添加键值对
字典名[ '键名' ] = 值
child = {'age':5, 'color':'red'}
child['height'] = 150
child['fruits'] = 'apple'
print(child)

3、创建空字典
child = {}
child['height'] = 150
child['fruits'] = 'apple'
print(child)

7312

被折叠的 条评论
为什么被折叠?



