字典 dict 类
info={
“K1”:“V1”, 键值对
“K2”:“V2”
}
字典的value是任何值
info={
"k1":18,
“k2”:True,
"k3":[
11,
[],
(),
22,
33,
{
"kk1":"vv1"
"kk2":"vv2"
"kk3":(11,22)
}
]
"k4":(11,22,33,44)
}
#布尔值 列表 字典不能作为字典里面的key,字典是无序的
#索引方式找到指定元素 info={ "k1":18, "k2":True, "k3":[ 11, [], (), 22, 33, { "kk1":"vv1", 'kk2':'vv2', "kk3":(11,22), } ], "k4":(11,22,33,44), } v=info['k3'][5]['kk3'][0] print(v)
输出 11
#删除指定元素 info={ "k1":18, "k2":True, "k3":[ 11, [], (), 22, 33, { "kk1":"vv1", 'kk2':'vv2', "kk3":(11,22), } ], "k4":(11,22,33,44), } del info['k1'] print(info)
输出
{'k2': True, 'k3': [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}], 'k4': (11, 22, 33, 44)}
#删除指定元素 info={ "k1":18, "k2":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, 'k2': True, 'k3': [11, [], (), 22, 33, {'kk2': 'vv2', 'kk3': (11, 22)}], 'k4': (11, 22, 33, 44)}
for循环
#for循环 info={ "k1":18, "k2":True, "k3":[ 11, [], (), 22, 33, { "kk1":"vv1", 'kk2':'vv2', "kk3":(11,22), } ], "k4":(11,22,33,44), } for item in info.keys(): print(item)
输出
k1
k2
k3
k4
#for循环 info={ "k1":18, "k2":True, "k3":[ 11, [], (), 22, 33, { "kk1":"vv1", 'kk2':'vv2', "kk3":(11,22), } ], "k4":(11,22,33,44), } for item in info.values(): print(item)
输出
18 True [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}] (11, 22, 33, 44)
#根据序列,创建字典,并制定统一的值 v=dict.fromkeys(['k1',123,"999"]) print(v) v1=dict.fromkeys(["k1",123,"999"],123) print(v1)
输出
{'k1': None, 123: None, '999': None} {'k1': 123, 123: 123, '999': 123}
#根据key获取值,key不存在时,可以指定值,默认为None dic={ "k1":'v1' } v=dic.get('k1',111) print(v) v1=dic.get('k111') print(v1) v2=dic.get('k1111',1111) print(v2)
输出
v1 None 1111
#删除 dic={ "k1":'v1', "k2":'v2' } v=dic.pop('k1') print(dic,v)
输出
{'k2': 'v2'} v1
#不存在,设置,获取当前key对应的值 dic={ "k1":'v1', "k2":'v2' } v=dic.setdefault('k111','123') print(dic,v)
输出
{'k1': 'v1', 'k2': 'v2', 'k111': '123'} 123
#更新 dic={ "k1":'v1', "k2":'v2' } dic.update(({'k1':'111','k2':'123'})) print(dic) dic.update({"k1":"123","k2":"123","k5":"asdf"}) print(dic)
输出
{'k1': '111', 'k2': '123'} {'k1': '123', 'k2': '123', 'k5': 'asdf'}