文章目录
1、字典的应用场景
字典里面以键值对的形式出现,字典数据和数据顺序没有关系。后期无论数据如何变化,只需要按照对应的键的名字查找数据即可。
2、创建字段的语法
2.1、特点:
符号位大括号 数据为键值对出现 各个键值对之间用逗号隔开
dict ={'name':'tom','age':'20','gender':'男'}
print(dict)
dict1 ={}
print(dict1)
3、字典的常见操作
3.1、新增
dict ={'name':'tom','age':'20','gender':'男'}
dict['name']='lily'
print(dict)
3.2、删除
dict ={'name':'tom','age':'20','gender':'男'}
del(dict)
del dict['name']
dict.clear()
3.3、修改
dict ={'name':'tom','age':'20','gender':'男'}
dict['name']='lily'
print(dict)
3.4、查找
3.4.1、按照key查找
dict ={'name':'tom','age':'20','gender':'男'}
print(dict['name'])
3.4.2、get() 若不存在,返回none
dict ={'name':'tom','age':'20','gender':'男'}
print(dict.get('name'))
print(dict.get('names'))
3.4.3、keys() 查找所有keys
3.4.4、value() 查找所有value
dict ={'name':'tom','age':'20','gender':'男'}
print(dict.keys())
print(dict.values())
3.4.5、items() 查找所有元组
4、字典的循环遍历
4.1、遍历字典key
dict ={'name':'tom','age':'20','gender':'男'}
for key in dict.keys():
print(key)
4.2、遍历字段value
dict ={'name':'tom','age':'20','gender':'男'}for value in dict.values(): print(value)
4.3、遍历字段的元素–键值对
dict ={'name':'tom','age':'20','gender':'男'}for item in dict.items(): print(item)
4.4、遍历字段的键值对(拆包)
dict ={'name':'tom','age':'20','gender':'男'}for item in dict.items(): print(item)