#字典 dict
#1.字典的格式:键值对
info = {'k1':'v1','k2':'v2'}
#2.字典的value可以是任何值
#3.列表、字典不能作为字典的key
#4.字典是无序的
info = {'k1': 18,
2: True,
'k3': [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}],
'k4': (11, 22, 33, 44)
}
v1 = info['k1']
v2 = info[2]
print(v1,v2)
运行结果:
18 True
#5.支持索引方式找到指定元素
#取到kk3中的11
info = {'k1': 18,
2: True,
'k3': [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}],
'k4': (11, 22, 33, 44)
}
v3 = info['k3'][5]['kk3'][0]
print(v3)
运行结果:
11
#6.字典支持del删除
info = {'k1': 18,
2: True,
'k3': [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}],
'k4': (11, 22, 33, 44)
}
del info['k1']
print(info)
运行结果:
{2: True, 'k3': [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}], 'k4': (11, 22, 33, 44)}
info = {'k1': 18,
2: True,
'k3': [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}],
'k4': (11, 22, 33, 44)
}
del info['k3'][5]['kk1']
print(info)
运行结果:
{'k1': 18, 2: True, 'k3': [11, [], (), 22, 33, {'kk2': 'vv2', 'kk3': (11, 22)}], 'k4': (11, 22, 33, 44)}
#7.支持for循环 for循环字典默认输出keys
info = {'k1': 18,
2: True,
'k3': [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}],
'k4': (11, 22, 33, 44)
}
for item in info:
print(item)
运行结果:
k1
2
k3
k4
------------------------------------------------------方法-----------------------------------------------------------
#输出key
for item in info.keys() :
print(item)
运行结果:
k1
2
k3
k4
#输出value
for item in info.values() :
print(item)
运行结果:
18
True
[11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}]
(11, 22, 33, 44)
#输出键值对
for item in info.items() :
print(item)
运行结果:
('k1', 18)
(2, True)
('k3', [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}])
('k4', (11, 22, 33, 44))
#
for k,v in info.items() :
print(k,v)
运行结果:
k1 18
2 True
k3 [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}]
k4 (11, 22, 33, 44)
#fromkeys是静态方法,根据序列创建字典,并指定统一的值
v = dict.fromkeys(['k1', 123, '999'], 123)
print(v)
运行结果:
{'k1': 123, 123: 123, '999': 123}
#get 根据key获取值,key不存在时,可以指定值(不指定,默认为None)
dic = {'k1': 'v1'}
v1 = dic.get('k1')
v2 = dic.get('k2')
v3 =dic.get('k2',111)
print(v1, v2,v3)
运行结果:
v1 None 111
#pop 删除并获取值
dic = {'k1': 'v1',
'k2': 'v2'}
v=dic.pop('k1')
print(dic,v)
运行结果:
{'k2': 'v2'} v1
#popitem 随机删一个键值对
#setdefault 设置key值(若key已存在,则不设置,获取当前可以对应的值)
dic = {'k1': 'v1',
'k2': 'v2'}
v1=dic.setdefault('k1',123)
v2=dic.setdefault('k3',222)
print(dic,v1,v2)
运行结果:
{'k1': 'v1', 'k2': 'v2', 'k3': 222} v1 222
#update 更新
#方式一
dic = {'k1': 'v1',
'k2': 'v2'}
dic.update({'k1':'111','k3':123})
print(dic)
运行结果:
{'k1': '111', 'k2': 'v2', 'k3': 123}
#方式二
dic = {'k1': 'v1',
'k2': 'v2'}
dic.update(k1=123,k3=456)
print(dic)
运行结果:
{'k1': 123, 'k2': 'v2', 'k3': 456}
#*** keys() values() items() get() update()必须掌握