字典和列表的区别:
- 字典和列表一样,都是python中的数据结构之一,是可变序列。
- 以键值对的形式存储数据,冒号之前的是键,冒号之后的是值。
- 列表使用 [ ] , 字典使用 { } 。
- 列表是有序序列,字典是无序的,存储位置经过 hash(key) 函数的计算可得。
字典的创建
- 花括号创建
scores = {'a': 100, 'b': 200, 'c': 300}
print(scores)
print(type(scores))
- 使用内置函数dict( )
student = dict(name='jack', age=20)
print(student)
print(type(student))
empty = dict() # 空字典
print(empty)
获取字典中的元素
- 使用方括号
scores = {'a': 100, 'b': 200, 'c': 300}
print(scores['a'])
- 使用get方法
print(scores.get('b'))
print(scores.get('z', 123)) # 可以通过参数设置默认的value,以便指定的key不存在时返回
上述两种方法的区别在于,使用方括号在查找不存在的元素时会报错:keyerror;使用get方法时会返回None而不报错,所以建议使用get方法查找。
键的判断
scores = {'a': 100, 'b': 200, 'c': 300}
print('z' not in scores)
键的删除
scores = {'a': 100, 'b': 200, 'c': 300}
del scores['a']
print(scores)
scores.clear() # 清空字典
print(scores)
键的新增和修改
# 键的新增
scores = {'a': 100, 'b': 200, 'c': 300}
scores['x'] = 90
print(scores)
# 键的修改
scores['x'] = 99
print(scores)
可以看出格式皆为scores[‘x’] = value,当key存在时修改,不存在时新增。
获取字典视图
- 获取所有的key
scores = {'a': 100, 'b': 200, 'c': 300}
keys = scores.keys()
print(keys)
print(type(keys))
- 获取所有的value
value = scores.values()
print(value)
print(type(value))
- 获取所有的key - value对
items = scores.items()
print(items)
print(list(items)) # 转换成列表,列表元素是由元组组成的
字典元素的遍历
for item in scores: # 输出所有的键和值
print(item, scores[item], scores.get(item))
字典生成式,使用内置函数zip( )打包
items = ['Book', 'Pen', 'Eraser']
price = [5, 3, 1]
dic = {items.upper(): price for items, price in zip(items, price)}
print(dic)
# upper(): 大写
注意事项:
- key不能重复,后面会把前面的覆盖
s = {'name': '张三', 'name': '李四'}
print(s['name'])
- 字典中的元素是无序的
- 字典中的key是不可变对象
- 字典会浪费较大的内存,是一种空间换时间的数据结构