python内置的数据结构之一,是一个可变序列
以键值对的形式存储数据,字典是一个无序的序列
字典示意图注:位置是由hash函数加工的来的
字典实现原理其原理和查字典的过程相似,python中的字典是根据key查找value所在的位置
字典的创建使用花括号去创建
scores = {'张三': 100, '李四': 98, '王五': 45}
print(scores)#{'张三': 100, '李四': 98, '王五': 45}
print(type(scores))#
使用内置函数dict()
student = dict(name='jack')
print(student)#{'name': 'jack'}
字典常用的操作
元素获取
key的判断
- in
- not in
'张三' in scores #存在返回True '张三' not in scores #不存在返回True元素的删除
del scores['张三'] #clear()会清空字典 scores.clear()元素的增加
scores['陈留']=98元素的修改
scores['陈留']=100获取字典视图
scores = {'张三': 100, '李四': 98, '王五': 45}
----------使用keys()获取字典中所有的key----------
keys = scores.keys()
print(keys) #dict_keys(['张三', '李四', '王五'])
print(type(keys)) #
print(list(keys)) #['张三', '李四', '王五']
----------使用values()获取字典中所有的value----------
values = scores.values()
print(values) #dict_values([100, 98, 45])
print(type(values)) #
print(list(values)) #[100, 98, 45]
----------使用items()获取字典中所有的key,value对----------
items = scores.items()
print(items) #dict_items([('张三', 100), ('李四', 98), ('王五', 45)])
print(type(items)) #
'''list()转换后是由元组构成的数列'''
print(list(items)) #[('张三', 100), ('李四', 98), ('王五', 45)]
字典的遍历
scores = {'张三': 100, '李四': 98, '王五': 45}
for item in scores:
print(item, scores[item], scores.get(item))
#张三 100 100
#李四 98 98
#王五 45 45
字典的特点
- 字典中的所有元素都是一个key-value对, key不允许重复, value可以重复
- 字典中的元素是无序的
- 字典中的key必须是不可变对象
- 字典也可以根据需要动态地伸缩
- 字典会浪费较大的内存,是一种使用空间换时间的数据结构
zip函数:用于将可迭代的对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的列表
items = ['Fruits', 'Books', 'Others'] prices = [98, 76, 85] print(type(zip(items, prices))) #for item, price in zip(items, prices): print(item, price) ''' Fruits 98 Books 76 Others 85 '''
items = ['Fruits', 'Books', 'Others']
prices = [98, 76, 85]
d = {fruit.upper(): price for fruit, price in zip(items, prices)}
print(d)#{'FRUITS': 98, 'BOOKS': 76, 'OTHERS': 85}



