Python学习.第六天.字典
前言
一、什么是字典?
字典是Python内置的数据结构之一,与列表一样是一个可变序列。
可变序列是指可以进行增删改的操作,反之,不可变序列就是不可以进行增删改操作。
以键值对的方式存储数据,字典是一个无序的序列。
eg:scores = {‘张三’:100,‘李四:98’,‘王五:45’}
冒号之前的称为 键,冒号之后的称为 值,整体称为键值对。
可以看到 key1的值第一个放到字典中的键,我们向字典中存储数据的时候,会经过一个hash()函数的工序,要把存储的键放到hash()函数中进行计算存储的位置,所以要求放到字典中的键,必须是一个不可变序列(整数序列、字符串序列)。
二、字典的原理
字典的实现原理与查字典类似,查字典是现根据部首或者拼音查找对应的页码,Python中的字典是根据key查找value所在的位置。
三、字典的创建与删除
(1)最常用的方式,使用花括号
(2)使用内置函数dict()
scores = {'one': 100, 'two': 200, 'three': 300}
print(scores)
print(type(scores))
print('-------------------------------------')
student = dict(name='jack', age=20)
print(student)
四、字典的查询操作
(1)[] 如果字典中不存在指定的key,抛出keyError异常。
(2)get()方法,如果字典中不存在指定的key,并不会抛出keyError而是返回None,可以通过参数设置默认的value,以便指定的key不存在时返回。
scores = {'one': 100, 'two': 200, 'three': 300}
print(scores['two'])
print(scores.get('two'))
print(scores.get('four'))
print(scores.get('three', 99)) # 查找three时 所对的value不存在时,提供的一个默认值
print(scores.get('four', 300))
五、字典元素的增、删、改操作
1.key的判断:
(1)in:指定的key在字典中存在返回True。
(2)not in:指定的key在字典中不存在返回True,存在就返回False。
scores = {'one': 100, 'two': 200, 'three': 300}
print('one' in scores)
print('four' not in scores) # 不存在就返回True
print('one' not in scores) # 存在就返回 False
2.字典元素的删除
del scores['one']
print(scores)
3.字典元素的新增
scores['four'] = 99
print(scores) #{'two': 200, 'three': 300, 'four': 99}
scores['four'] = 100
print(scores) # {'two': 200, 'three': 300, 'four': 100}
如果增加的字典key与已有的相同,则自动更新覆盖原字典的value。
4.获取字典视图的三个方法
(1)keys():获取字典中所有的key
(2)values():获取字典中所有的value
(3)items():获取字典中所有的key、value对
scores = {'one': 100, 'two': 200, 'three': 300}
keys = scores.keys()
print(keys)
print(type(keys))
print(list(keys)) # 将所有的key组成的视图转成列表
# 获取都有的value
values = scores.values()
print(values)
print(type(values))
print(list(values))
# 获取所有的key—value对
items = scores.items()
print(items)
print(list(items)) # 转换之后的列表元素是由元组组成的
5.字典元素的遍历
scores = {'one': 100, 'two': 200, 'three': 300}
for _ in scores: # _ 作为变量
print(_, scores[_])
print('---------------------------------------')
scores = {'one': 100, 'two': 200, 'three': 300}
for _ in scores:
print(_, scores[_], scores.get(_))
六、字典生成式
内置函数zip():
用于将可迭代的对象作为参数,将对象中对应的元素打包成一个元组,然后返回有这些元组组成的列表。
items = ['fruits', 'books', 'others']
prices = [96, 78, 65]
d = {items: prices for items, prices in zip(items, prices)}
print(d)
a = {prices: items.upper() for prices, items in zip(prices, items)}
print(a)
# 如果两个元素之间的个数不相等,以元素短的为准生成
总结
字典的特点:
(1):字典中的所有元素都是一个key—value对,key不允许重复,value可以重复。
(2):字典中的元素时无序的。
(3):字典中的key必须是不可变对象
(4):字典也可以根据动态地伸缩
(5):字典会浪费较大的内存,是一种使用空间换时间的数据结构。