一、dict 基本格式
① 大括号包括内容,"k1":'v1'为一对键值对
{
# "k1": 'v1', #键值对
# "k2": 'v2'
# }
② 布尔值(1,0)、列表、字典不能作为字典的key
③ 字典的value可以是任何值
④ 字典无序
二、函数与用法
① 索引
dic = {'k1':'jio',"k2":123,"k3":'qqq','k999':(11,22,33),'kk2':{'oo1':666}} v = dic['k1'] v2 = dic['kk2']['oo1'] print(v) print(v2)
输出结果:
jio
666
② dict.fromkeys #根据序列,创建字典,并指定统一的值
v = dict.fromkeys(['k2',156,"554"],546) #ke,156,554均为K值,546为v值 print(v)
输出结果:{156: 546, 'k2': 546, '554': 546}
③ .pop() #删除并获取值
dic = {'k1':'jio',"k2":123,"k3":'qqq'} v= dic.pop('k1') print(dic,v)
输出结果:{'k3': 'qqq', 'k2': 123} jio
.popitem() #删除并获取值,默认删除最后一组
dic = {'k1':'jio',"k2":123,"k3":'qqq'} k,v = dic.popitem() print(dic) print(k) print(v)
输出结果:
{'k2': 123, 'k1': 'jio'}
k3
qqq
④ .get() #根据Key获取值,key不存在时,可以指定默认值(None)
dic = {'k1':'jio',"k2":123,"k3":'qqq'} v = dic.get('k1') print(v) v2 = dic.get('k22',1234) print(v2)
输出结果:
jio
1234
⑤ .setdefault() #设置值,
# 已存在,不设置,获取当前key对应的值
# 不存在,设置,获取当前key对应的值
dic = {'k1':'jio',"k2":123,"k3":'qqq'} v = dic.setdefault('k13',77) print(v) v2 = dic.setdefault('k3') print(v2)
输出结果:
77
qqq
⑥ .update() #更新
dic = {'k1':'jio',"k2":123,"k3":'qqq'} dic.update({'k1':'OP',"K4":123,'K999':4}) print(dic)
输出结果:
{'k1': 'OP', 'K999': 4, 'k3': 'qqq', 'K4': 123, 'k2': 123}
dic = {'k1':'jio',"k2":123,"k3":'qqq'} dic.update(k1=123,k4='abcdd',k000='ok') print(dic)
输出结果:
{'k4': 'abcdd', 'k1': 123, 'k2': 123, 'k3': 'qqq', 'k000': 'ok'}
⑦ del #删除
dic = {'k1':'jio',"k2":123,"k3":'qqq','k999':(11,22,33),'kk2':{'oo1':666}} del dic['kk2']['oo1'] print(dic)
输出结果:
{'k1': 'jio', 'k999': (11, 22, 33), 'k2': 123, 'k3': 'qqq', 'kk2': {}}
⑧ for循环
dic = {'k1':'jio',"k2":123,"k3":'qqq','k999':(11,22,33),'kk2':{'oo1':666}} for item in dic : print(item)
输出结果:
k2
k1
kk2
k999
k3
dic = {'k1':'jio',"k2":123,"k3":'qqq','k999':(11,22,33),'kk2':{'oo1':666}} for item in dic.keys() : #输出K值 print(item)
输出结果:
k2
k1
kk2
k999
k3
dic = {'k1':'jio',"k2":123,"k3":'qqq','k999':(11,22,33),'kk2':{'oo1':666}} for item in dic.values() : #输出v值 print(item)
输出结果:
123
{'oo1': 666}
qqq
(11, 22, 33)
jio