python的字典的函数 python字典常用方法( 七 )


d=dict.fromkeys(['one','two','three'],'unknow')
printd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':'unknow','two':'unknow','one':'unknow'}
3.4 get函数:访问字典成员
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printd.get('one')
printd.get('four')
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
1
None
注:get函数可以访问字典中不存在的键,当该键不存在是返回None
3.5 has_key函数:检查字典中是否含有给出的键
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printd.has_key('one')
printd.has_key('four')
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
True
False
3.6 items和iteritems函数:items将所有的字典项以列表方式返回 , 列表中项来自(键,值),iteritems与items作用相似,但是返回的是一个迭代器对象而不是列表
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
list=d.items()
forkey,valueinlist:
printkey,':',value
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
three :3
two :2
one :1
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
it=d.iteritems()
fork,vinit:
print"d[%s]="%k,v
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
d[three]=3
d[two]=2
d[one]=1
3.7 keys和iterkeys:keys将字典中的键以列表形式返回,iterkeys返回键的迭代器
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printu'keys方法:'
list=d.keys()
printlist
printu'\niterkeys方法:'
it=d.iterkeys()
forxinit:
printx
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
keys方法:
['three','two','one']
iterkeys方法:
three
two
one
3.8 pop函数:删除字典中对应的键
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
d.pop('one')
printd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
{'three':3,'two':2}
3.9 popitem函数:移出字典中的项
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
d.popitem()
printd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
{'two':2,'one':1}
3.10 setdefault函数:类似于get方法,获取与给定键相关联的值,也可以在字典中不包含给定键的情况下设定相应的键值
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printd.setdefault('one',1)
printd.setdefault('four',4)
printd
运算结果:
{'three':3,'two':2,'one':1}
{'four':4,'three':3,'two':2,'one':1}
3.11 update函数:用一个字典更新另外一个字典
# _*_ coding:utf-8 _*_
d={
'one':123,
'two':2,
'three':3
}
printd
x={'one':1}
d.update(x)
printd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':123}
{'three':3,'two':2,'one':1}
3.12 values和itervalues函数:values以列表的形式返回字典中的值 , itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重复的元素

推荐阅读