Python学习Day8--dict字典
程序员文章站
2022-07-15 08:02:46
...
dict类
info = {key:value}
字典的value可以为任何值
列表,字典不能作为字典的key
字典key按照哈希表来保存,key会转换成哈希值。
但是字典是无序的
通过索引[key]来找到指定元素
info = {
'k1':18,
2 : True,
'k3':[
11,
22,
33,
{
'kk1':'vv1',
'kk2':'vv2',
'kk3':(11,22),
}
],
'k4':(11,22,33,44)
}
v = info['k3'][3]['kk3'][1]
print(v)
输出结果:
22
支持for循环,但不支持while循环
info = {
'k1':18,
2 : True,
'k3':[
11,
22,
33,
{
'kk1':'vv1',
'kk2':'vv2',
'kk3':(11,22),
}
],
'k4':(11,22,33,44)
}
for i in info.keys():
print(i)
输出结果:
k1
2
k3
k4
info = {
'k1':18,
2 : True,
'k3':[
11,
22,
33,
{
'kk1':'vv1',
'kk2':'vv2',
'kk3':(11,22),
}
],
'k4':(11,22,33,44)
}
for i in info.values():
print(i)
输出结果:
18
True
[11, 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}]
(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)
}
for i in info.keys():
print(i,info[i])
输出结果:
k1 18
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)
}
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)
支持del删除
如果key值重复,只取一个