字典类型dict
======================================基本使用======================================
1、用途:记录多个值,列表是索引对应值,而字典是key对应值,其中key对value有描述性的功能
2、定义方式:在{}用逗号分隔开多个元素,每个元素都是key:value的形式,其中key可以不可变类型,通常是字符串类型
而value可以是任意类型
d={1:'aaa',2.2:'bbb','xxx':'ccc',(1,2,3):'dddd'} #d=dict(...)
print(d[(1,2,3)])
类转换
d=dict(x=1,y=2,z=3)
print(d)
items=[('name','egon'),('age',18),('gender','male')]
d={}
for item in items:
d[item[0]]=item[1]
d=dict(items)
print(d)
了解
keys=['name','age','gender','height','weight']
d={}
for key in keys:
d[key]=None
d={}.fromkeys(keys,None)
print(d,type(d))
3、常用操作+内置的方法
优先掌握的操作:
1、按key存取值:可存可取
dic={'name':'egon','age':18}
dic['xxxx']
print(dic.get('name'))
print(dic.get('xxx'))
print(dic['name'])
dic['name']='EGON'
dic['gender']='male'
print(dic)
l=['a','b','c']
l[0]='A'
l[4]='AAA'
2、长度len
dic={'name':'egon','age':18}
print(dic)
print(len(dic))
3、成员运算in和not in :是以字典的key为准的
dic={'name':'egon','age':18}
print('name' in dic)
print('egon' in dic)
4、删除
dic={'name':'egon','age':18}
del dic['name']
print(dic)
res=dic.pop('name')
print(dic)
print(res)
res=dic.popitem()
print(res)
5、键keys(),值values(),键值对items()
在python2
>>> dic={'name':'egon','age':18}
>>>
>>>
>>> dic.keys()
['age', 'name']
>>>
>>>
>>> dic.values()
[18, 'egon']
>>>
>>>
>>> dic.items()
[('age', 18), ('name', 'egon')]
在python3
>>> dic={'name':'egon','age':18}
>>>
>>> dic.keys()
dict_keys(['name', 'age'])
>>> dic.values()
dict_values(['egon', 18])
>>> dic.items()
dict_items([('name', 'egon'), ('age', 18)])
6、循环
dic={'name':'egon','age':18}
for k in dic:
print(k)
for k in dic.keys():
print(k)
for v in dic.values():
print(v)
for k,v in dic.items(): #k,v=('name', 'egon')
print(k,v)
需要掌握的操作
dic={'name':'egon','age':18}
dic={'name':'egon','age':18}
dic.update({'age':19,'gender':'male'})
print(dic)
dic={'name':'egon','age':18}
当key存在时,不改原值,返回原值
res=dic.setdefault('name','EGON')
print(dic)
print(res)
当key不存在时,增加新值
res=dic.setdefault('gender','male')
print(dic)
print(res)
======================================该类型总结====================================
存多个值
无序
可变(1、可变:值变,id不变。可变==不可hash 2、不可变:值变,id就变。不可变==可hash)