key函数python key函数是什么意思( 三 )


printy
printx
printu'删除Y中的值,观察输出'
y['test'].remove('c')
printy
printx
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
初始X字典:
{'test': ['a','b','c'],'three':3,'two':2,'one':1}
X复制到Y:
Y字典:
{'test': ['a','b','c'],'one':1,'three':3,'two':2}
修改Y中的值,观察输出:
{'test': ['a','b','c'],'one':1,'three':33,'two':2}
{'test': ['a','b','c'],'three':3,'two':2,'one':1}
删除Y中的值,观察输出
{'test': ['a','b'],'one':1,'three':33,'two':2}
{'test': ['a','b'],'three':3,'two':2,'one':1}
注:在复制的副本中对值进行替换后,对原来的字典不产生影响 , 但是如果修改了副本 , 原始的字典也会被修改 。deepcopy函数使用深复制,复制其包含所有的值,这个方法可以解决由于副本修改而使原始字典也变化的问题 。
# _*_ coding:utf-8 _*_
fromcopyimportdeepcopy
x={}
x['test']=['a','b','c','d']
y=x.copy()
z=deepcopy(x)
printu'输出:'
printy
printz
printu'修改后输出:'
x['test'].append('e')
printy
printz
运算输出:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
输出:
{'test': ['a','b','c','d']}
{'test': ['a','b','c','d']}
修改后输出:
{'test': ['a','b','c','d','e']}
{'test': ['a','b','c','d']}
3.3 fromkeys函数:使用给定的键建立新的字典,键默认对应的值为None
# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'])
printd
运算输出:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':None,'two':None,'one':None}
或者指定默认的对应值
# _*_ coding:utf-8 _*_
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

推荐阅读