dict 有索引,可变
目录
创建
em={}
em=dict()
print(em)
查
访问项目
索引访问
em={1:2,2:'ss',(1,2):2}
em[1]='tt'
print(em[1])
get()方法访问
em={1:2,2:'ss',(1,2):2}
em[1]='tt'
x=em.get(1)
print(x)
遍历字典
默认遍历字典的键,也有返回值的方法。values()返回值。items()遍历值和键。
for i in em:
print(i,end=' ')
for i in em:
print(em[i],end=' ')
for i in em.values():
print(i)
for x,y in em.items():
print(x,y)
查键是否存在 in
if (1,2) in em:
print('yes')
改
em={1:2,2:'ss',(1,2):2}
em[1]='tt'
增
通过使用新的键值为其赋值,将项目添加。
em={1:2,2:'ss',(1,2):2}
em[1]='tt'
em['与']=3
print(em)
删
因为有key,dict的删比较特殊。pop() 和popitem() del clear
popitem() 3.7之前版本删除随机项,之后的是删除最后插入项目。
del em 删除字典
em.clear()清空字典
em.pop('与')
em.popitem()
print(em)
del em[1]
print(em)
del em
em={'yy':2,'vv':'语音'}
em.clear()
print(em)
字典的复制
copy()方法
dict()方法
yy=em.copy()
zz=dict(em)
print(yy)
print(zz)