python函数与字典 python 函数字典( 六 )


printd['one']
printd['three']
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
items中的内容:
[('one',1), ('two',2), ('three',3), ('four',4)]
利用dict创建字典,输出字典内容:
{'four':4,'three':3,'two':2,'one':1}
查询字典中的内容:
或者通过关键字创建字典
# _*_ coding:utf-8 _*_
d=dict(one=1,two=2,three=3)
printu'输出字典内容:'
printd
printu'查询字典中的内容:'
printd['one']
printd['three']
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
输出字典内容:
{'three':3,'two':2,'one':1}
查询字典中的内容:
二、字典的格式化字符串
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
printd
print"three is %(three)s."%d
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four':4,'three':3,'two':2,'one':1}
threeis3.
三、字典方法
3.1 clear函数:清除字典中的所有项
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
printd
d.clear()
printd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four':4,'three':3,'two':2,'one':1}
{}
请看下面两个例子
3.1.1
# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
printdd
d={}
printd
printdd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two':2,'one':1}
{}
{'two':2,'one':1}
3.1.2
# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
printdd
d.clear()
printd
printdd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two':2,'one':1}
{}
{}
3.1.2与3.1.1唯一不同的是在对字典d的清空处理上 , 3.1.1将d关联到一个新的空字典上,这种方式对字典dd是没有影响的,所以在字典d被置空后,字典dd里面的值仍旧没有变化 。但是在3.1.2中clear方法清空字典d中的内容,clear是一个原地操作的方法,使得d中的内容全部被置空,这样dd所指向的空间也被置空 。
3.2 copy函数:返回一个具有相同键值的新字典
# _*_ coding:utf-8 _*_
x={'one':1,'two':2,'three':3,'test':['a','b','c']}
printu'初始X字典:'
printx
printu'X复制到Y:'
y=x.copy()
printu'Y字典:'
printy
y['three']=33
printu'修改Y中的值,观察输出:'
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()

推荐阅读