dict 字典类型
dict用于存储一组或多组数据,dict使用大括号{}进行定义
dict是键值对的存储方式,name:admin
键和值之间使用“:”分隔,多组键值对之间使用“,”分隔
键必须是字符串或数字类型,值可以是任意类型
键命不能重复,值可以重复
# 例:记录一本书的相关数据
vard = {'title':'<<Walden>>','author':'Thoreau','price':20}
print(vard,type(vard))
# 获取字典中的值
print(vard['title'])
# 字典中键名不能重复,否则会覆盖
vard = {1:100,2:200,1:'10'}
print(vard)
{'title': '<<Walden>>', 'author': 'Thoreau', 'price': 20} <class 'dict'>
<<Walden>>
{1: '10', 2: 200}
dict定义方式
# {key:value,key:value}
vardict = {1:'a','2':2,'c':'3'}
print(vardict)
# dict(key=value,key=value)
vardict = dict(name='a',age=1)
print(vardict)
# dict(),数据类型转换,参数必须是二级容器,且每个二级元素中只有两个元素
G = ((1,{'a','A'}),[2,{'b':'B'}],{3:'c',4:'d'},{5,('e','E')})
F = [(1,['a','A']),[2,{'b':'B'}],{3:'c',4:'d'},{('e','E'),5}]
H = {(6,'f'),(7,'g')}
print(dict(G))
print(dict(F))
print(dict(H))
# zip()、dict(),先压缩,再数据类型转换
var1 = [1,2,3,4]
var2 = ('a','b','c','d')
res1 = list(zip(var1,var2))
print(res1)
res2 = dict(res1)
print(res2)
{1: 'a', '2': 2, 'c': '3'}
{'name': 'a', 'age': 1}
{1: {'a', 'A'}, 2: {'b': 'B'}, 3: 4, 5: ('e', 'E')}
{1: ['a', 'A'], 2: {'b': 'B'}, 3: 4, 5: ('e', 'E')}
{7: 'g', 6: 'f'}
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
dict数据操作
# dict不能使用 +、* 进行拼接或复制
vardict = {1:'a',2:2,'3':'c','d':4}
# 获取
print(vardict[1],end=' ')
print(vardict['3'])
# 修改
vardict[2] = 22
print(vardict)
# 添加,若key重复,则会覆盖
vardict['D'] = 5
print(vardict)
vardict['D'] = 555
print(vardict)
# 删除
del vardict['D']
print(vardict)
# 成员检测
res1 = 'd' in vardict
res2 = 4 in vardict
print(res1)
print(res2)
a c
{1: 'a', 2: 22, '3': 'c', 'd': 4}
{1: 'a', 2: 22, '3': 'c', 'd': 4, 'D': 5}
{1: 'a', 2: 22, '3': 'c', 'd': 4, 'D': 555}
{1: 'a', 2: 22, '3': 'c', 'd': 4}
True
False
dict函数
vardict = {1:'a',2:2,'3':'c','d':4}
# len()
res = len(vardict)
print(res)
# dict.keys()
# 功能:获取dict中所有的key
res = vardict.keys()
print(res,type(res))
# dict.values()
# 功能:获取dict中所有的value
res = vardict.values()
print(res,type(res))
# dict.items()
# 功能:获取dict中所有的键值对
res = vardict.items()
print(res,type(res))
4
dict_keys([1, 2, '3', 'd']) <class 'dict_keys'>
dict_values(['a', 2, 'c', 4]) <class 'dict_values'>
dict_items([(1, 'a'), (2, 2), ('3', 'c'), ('d', 4)]) <class 'dict_items'>
遍历dict
vardict = {1:'a',2:2,'3':'c','d':4}
# (1).直接遍历dict
for i in vardict :
print(i,end=' ')
print(vardict[i])
# (2).遍历dict.items()
for i in vardict.items() :
print(i)
for k,v in vardict.items() :
print(k,v)
# (3).遍历dict中所有key
for i in vardict.keys() :
print(i,end=' ')
print()
# (4).遍历dict中所有value
for i in vardict.values() :
print(i,end=' ')
1 a
2 2
3 c
d 4
(1, 'a')
(2, 2)
('3', 'c')
('d', 4)
1 a
2 2
3 c
d 4
1 2 3 d
a 2 c 4