创建字典
字典特点:
- 符号为大括号
- 数据为键值对形式出现
- 各个键值对之间用逗号隔开
# 什么叫键 key
# 1 有数据的字典
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
print(dict1)
print(type(dict1))
# 2 空字典
dict2 = {}
print()
dict3 = dict()
print(dict2, dict3, type(dict2), type(dict3))
常见操作
增
写法: 字典序列[key] = 值
dict1['id'] = 110
dict1['name'] = 'Rose'
print(dict1)
'''
{'name': 'Rose', 'age': 20, 'gender': '男', 'id': 110}
'''
删
- del()/del 键值对:
- clear():
# del
del dict1['name']
print(dict1)
# del(dict1)
# clear
dict1.clear()
print(dict1)
'''
{'age': 20, 'gender': '男'}
{}
'''
改
写法:字典序列[key] = 值
查
key值查找
如果key值存在,则返回对应的值,否则报错
print(dict1['name']) # 返回对应值
print(dict1['names']) # 报错
函数查找
- get()
字典序列.get(key, 默认值)
key存在时,返回对应值,不存在时,默认返回None,或者自定义值
- keys():
print(dict1.keys())
keys = dict1.keys()
print(keys)
'''
dict_keys(['name', 'age', 'gender'])
dict_keys(['name', 'age', 'gender'])
'''
- values():
print(dict1.values())
'''
dict_values(['Tom', 20, '男'])
'''
- items():
print(dict1.items())
'''
dict_items([('name', 'Tom'), ('age', 20), ('gender', '男')])
'''
返回而可迭代对象
字典的循环遍历
遍历字典的key
for key in dict1.keys():
print(key)
遍历字典的value
for value in dict1.values():
print(value, end='---')
遍历字典的元素
for item in dict1.items():
print(item, end='---')
遍历字典的键值对
for key, value in dict1.items():
print(f'{key} = {value}', end=' ')
'''
输出结果:
name---age---gender---
Tom---20---男---
('name', 'Tom')---('age', 20)---('gender', '男')---
name = Tom age = 20 gender = 男
'''