1、字典的定义
字典是一个无序的数据集合,使用print输出字典时
通常输出的顺序和定义的顺序不一致
1、字典的创建:
s = {} ###创建一个空字典
2、字典:key-value 键值对
一个字典是按照关键字存储值的集合,这些关键字了类似于下标运算符。在一个列表中,下标是整数,在一个字典中,关键字必须时与各可哈希对象。一个字典不能包含有重复的关键字。每个关键字都对应在各一个值。一个关键字和它对应的值形成存储在字典中的一个条目,如下图所示。
s = {
'user':['root','admin','student'],
'passwd':['123','456','789']
}
print(s)
3、工厂函数
Dict = dict()
print(Dict)
print(type(Dict))
d1 = dict(a = 1,b = 2)
print(d1)
print(type(d1))
4、字典的嵌套
students = {
'03151208':{
'name':'sql',
'age':'18',
},
'03151202':{
'name':'key',
'age':'18'
}
}
print(students['03151202']['name'])
print(students['03151208'])
5、所有的key和value值是一样的情况
print({}.fromkeys({'1','2'},'03151200'))
2、字典的特性
1、字典不支持索引
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict['1'])
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict[1])
2、字典不支持切片
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict[:])
3、字典的重复和连接无意义,因为字典的key值是唯一的
4、成员操作符:in和not in
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print('1' in Dict)
print('4' in Dict)
5、for循环,遍历字典的key值
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
for key,value in Dict.items():
print(key,value)
print("*************")
for key in Dict:
print(key,Dict[key])
3、字典的增加
1、增加一个元素
如果key值存在,则更新对应的value值,如果key值不存在,则添加对用的key-value值
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict)
Dict['4'] = 'banana'
Dict['2'] = 'cherry'
print(Dict)
2、添加多个key-value值
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
Dict_Backup = {
'5': 'lemon',
'6': 'pineapple',
'7': 'peach',
}
print(Dict)
Dict.update(Dict_Backup)
print(Dict)
3、setdefault添加key值
如果key值存在,不做修改
如果key值不存在,则添加对应的key-value
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict)
Dict.setdefault('1','grape')
print(Dict)
Dict.setdefault('5','Mango')
print(Dict)
4、字典的删除
1、del删除
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict)
del Dict['1']
print(Dict)
2、pop删除指定key值的key-value
如果key值存在,删除,并且返回删除key值对应的value
如果key值不存在,报错
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict)
item1 = Dict.pop('1')
print(item1)
print(Dict)
3、清空字典所有内容
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict)
Dict.clear()
print(Dict)
5、字典的查看
1、查看字典的key值
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict.keys())
2、查看字典的value值
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict.values())
3、查看key对应的value值
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict['2'])
###查看key的value值:get
若key存在,返回valkue值
若key值不存在,返回None
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict)
print(Dict.get('1'))
print(Dict.get('5'))
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
print(Dict.get('5','key not existed'))
print(Dict.get(('1')))
4、遍历
Dict = {
'1':'apple',
'2':'orange',
'3':'pear'
}
for k,v in Dict.items():
print(k,':',v)