python字典笔记(功能)

来源:互联网 发布:java鱼雷2 编辑:程序博客网 时间:2024/06/03 20:34

1.字典的引用

>>> import sys
>>> data={'platform':sys.platform,'spam':'laptop'}
>>> 'my {spam:<8} go {platform:>8}'.format(**data)
'my laptop   go    win32'
>>> 



>>> 'my %(spam)-8s go %(platform)8s'  % data
'my laptop   go   darwin'




2.释放中变量的引用 del 变量


3.查询变量被引用的次数(引用为0变量被自动释放)
>>> import sys
>>> sys.getrefcount(list)
50
>>> sys.getrefcount(n1)
>>>2


4.字典中查询不存在的键会报错(设置默认返回值)
KeyError: 'name1'
 D.get('height',180)
>>>180


5.字典初始化所有键值
dict.fromkeys(['a','b'],)
{'a': None, 'b': None}
默认为空,逗号后指定默认值


6.使用zip和dict内置函数构造字典集合
dict(zip(['name','age','height'],['bob',25,180]))
{'age': 25, 'name': 'bob', 'height': 180}


D={c.lower(): c+ '!' for c in ['big','world']}
>>> D
{'big': 'big!', 'world': 'world!'}


7.python 3.0  字典对象key值支持集合运算"&","|" ;value 不支持