4.字典Dict {}
字典定义了键和值之间一对一的关系,但它们是以无序的方式储存的。
- Dictionary 不只是用于存储字符串。Dictionary 的值可以是任意数据类型,包括字符串、整数、对象,甚至其它的 dictionary。
- 在单个 dictionary 里,dictionary 的值并不需要全都是同一数据类型,可以根据需要混用和匹配。
4.1创建Dict
dict1={"ID":"L100","Name":"COCO"}
students=[{'name':'n1','id':'001'},{'name':'n2','id':'002'},{'name':'n3','id':'003'}]
print('显示该数据结构类型',type(dict1))
dict1
demo_dict=dict(zip('abc','123')) #配对组成字典
demo_dict
4.2 Dict查询操作
print('常规查询\n',students[0]['id'])
print('根据键查询\n',students[0].get('id'))
4.3 Dict增加操作
students.append({'name':'n4','id':'004'}) #在最后面增加一个字典对象
print('添加一个字典对象后\n',students)
students[0]['school']='school1'#在列表的第一个字典中增加键值对
students[1]['school']='school2'
students[2]['school']='school3'
students[2]['school']='school3'
print('增加键值对后的字典\n',students)
4.4 Dict删除操作
del students[3]
print('删除列表中的一个字典对象后\n',students)
students[0].pop('id')
print('删除一个键值对后\n',students)
dict1.cleat() #清除所有元素
for i in range(0,len(students)):
students[i].pop('school')
students
4.5 Dict修改操作
students[0].update({'id':'001'}) #在列表第一个的第一个字典元素中修改键值对
print('更新后的字典\n',students)
4.6 Dict转换为其它数据结构
print("字典值转List",list(demo_dict).values())
print("字典键转List",list(demo_dict).key())