25:字典1

一、键(key)、值(value、hash) 、键值对:字典的项

二、创建和访问字典

1.例子

>>>dict1 = {'Lining':'一切皆有可能','nike':'just do it ','adidas':'impossible is nothing','vans':'编程改变世界'}

>>>print('Lining的口号是:', dict1['Lining'])

2.空字典

>>>dict2 = {}

3.dict(mapping):创建一个字典,mapping(唯一参数)可以是元组或列表

>>>dict3=dict(((1,'one'),(2,'two'),(3,'three'),(4,'four')))    

 #等价于dict3=dict([(1,'one'),(2,'two'),(3,'three'),(4,'four')])

>>>dict3

{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

关键字参数写法:dict4=dict(a='one', b='two', c='three', d='four')

注意:key不能是一个表达式,应是一个未添加引号的字符串,如  a  或asd 或阿斯顿

4.修改键对应的值

>>>dict4['a'] =  '我是1''

>>>dict4

{'c': 'three', 'a': '我是1', 'd': 'four', 'b': 'two'}

无此键,则自动在字典中添加

>>>dict4['e'] = 'five'

>>>dict4

{'c': 'three', 'a': '我是1', 'd': 'four', 'b': 'two', 'e': 'five'}

猜你喜欢

转载自blog.csdn.net/weixin_41004521/article/details/81124112