字典里面的数据是以键值对形式出现,字典数据和数据顺序没有关系。即字典不支持下标,后期无论数据如何变化,只需要按照对应的键的名字查找数据即可。
创建字典的语法字典的特点:
符号为大括号
数据为键值对形式出现
各个键值对之间用逗号隔开
#有数据字典
dict1 = {'name':'Jason','age':'23','gender':'男'}
#创建空字典
dict2 = {}
dict3 = dict()
注意:冒号前面的为键(key),冒号后面的值为(value)
字典常见操作增加
写法:字典序列[key] = 值
dict1 = {'name':'Jason','age':'23','gender':'男'}
dict1['name'] = 'Tom'
print(dict1)
#结果 {'name':'Tom','age':'23','gender':'男'}
dict1['id'] = '123'
print(dict1)
#结果 {'name':'Tom','age':'23','gender':'男','id' : '123'}
注意:如果key存在则修改这个key对应的值;如果key不存在则新增此键值对。字典为可变类型
删除
del() / del
删除字典或删除字典中指定键值对
dict1 = {'name':'Jason','age':'23','gender':'男'}
del dict1['gender']
print(dict1)
#结果['name':'Jason','age':'23']
clear():清空字典
dict1.clear()
注意:保留空字典
修改
写法:字典序列[key] = 值
与增用法相同
查找
key值查找
dict1 = {'name':'Jason','age':'23','gender':'男'}
print(dict1['gender'])
#结果 男
print(dict1['id'])
#结果 报错
注意:如果当前查找的key存在,则返回对应的值,否则报错
get()
语法:字典序列.get(key,默认值)
dict1 = {'name':'Jason','age':'23','gender':'男'}
print(dict1.get('name')) #Tom
print(dict1.get('id',123)) #123
print(dict1.get('id')) #None
注意:如果当前查找的key不存在则返回第二个参数(默认值),如果省略第二个参数,则返回None
keys()
查找字典中所有的key,返回可迭代对象。
dict1 = {'name':'Jason','age':'23','gender':'男'}
print(dict1.keys())
#dict_keys(['name','age','gender'])
values()
查找字典中所有的value,返回可迭代对象。
dict1 = {'name':'Jason','age':'23','gender':'男'}
print(dict1.values())
#dict_keys(['Jason','23','男'])
items()
查找字典中所有的键值对,返回可迭代对象。里面的数据是元组,其中元组数据1是key,数据2是value
dict1 = {'name':'Jason','age':'23','gender':'男'}
print(dict1.items())
#dict_keys([('name','Jason'),('age','23'),('gender','男')])
字典的循环遍历
遍历字典的key
dict1 = {'name':'Jason','age':'23','gender':'男'}
for i in dict1.keys():
print(i)
遍历字典的value
dict1 = {'name':'Jason','age':'23','gender':'男'}
for i in dict1.values():
print(i)
遍历字典的元素
dict1 = {'name':'Jason','age':'23','gender':'男'}
for i in dict1.items():
print(i)
遍历字典的键值对
dict1 = {'name':'Jason','age':'23','gender':'男'}
for key,value in dict1.items():
print(f'{key} = {value}')



