字典的特点
1、字典中的所有元素都是一个key-value对,key不允许重复,value可以重复
2、字典中的元素是无序的
3、字典中的key必须是不可变对象
4、字典也可以根据需要动态的伸缩
5、字典会浪费较大的内存,是一种使用空间交换时间的数据结构
字典的创建
创建字典有三种方式:
1、采用{ }
2、使用内置函数dict()
3、字典生成式
代码展示:
# 字典的创建方式:
scores = {'张山': 100, '李素': 90, '赵四': 150}
print(type(scores))
print(scores)
# 内置函数dict()
student = dict(name='张山', age=98)
print(student)
# 字典生成式
key = ['f', 'a', 'b', 'c', 'd']
value = [100, 98, 78, 89]
price = {key: value for key, value in zip(key, value)}
print(price)
运行结果:
获取字典中的value
获取字典中的value的两种方式:
1、字典名[key]
2、字典名.get(key)
代码展示:
scores = {'张山': 100, '李素': 90, '赵四': 150}
print(scores.get('张山'))
print(scores.get("张"))
print(scores['张山'])
print(scores['zhang']) # KeyError: 'zhang'
运行结果:
重点: 采用“字典名[key]”的方式获取字典中不存在的key的值时,会报错,如上图所示;而采用get方式获取字典中不存在的key的值时,不会报错,会输出None
删除key-value对
删除key-value对有两种方式:
1、del 字典名[key]
2、字典名.pop(key)
3、字典名.clear()
代码展示:
scores = {'张山': 100, '李素': 90, '赵四': 150}
del scores['张山']
print(scores)
scores.pop('李素')
print(scores)
运行结果:
修改/新增字典中的元素
字典名[key] = value
代码展示:
scores = {'张山': 100, '李素': 90, '赵四': 150}
scores['张山'] = 123
print(scores)
scores['李六'] = 145
print(scores)
运行结果:
获取字典视图
获取字典视图的三种方式:
1、获取字典中所有的key:keys()
2、获取字典中所有的Value:values()
3、获取字典中所有的key:value对:items()
代码展示:
scores = {'张山': 100, '李素': 90, '赵四': 150}
key = scores.keys()
print(list(key))
dai
value = scores.values()
print(list(value))
item = scores.items()
print(list(item))
运行结果:
字典元素遍历
代码展示:
scores = {'张山': 100, '李素': 90, '赵四': 150}
for item in scores:
print(item, scores[item])
运行结果: