《python基础教程(第二版)》学习笔记 字典(第4章)
创建字典:
d={'key1':'value1','key2':'value2'}
lst=[('key1','value1'),('key2','value2')]; d=dict(lst)
d=dict(key1='value1', key2='value2')
字典基本操作:
d={'key1':'value1','key2':'value2'}; len(d) ==> 2 #字典中的键值对数量
d={'key1':'value1','key2':'value2'}; d['key1'] ==> 'value1' # 键为k的值
d={'key1':'value1','key2':'value2'}; d['key1']='NewValue' ==> 'key1': 'NewValue' # 赋值
d={'key1':'value1','key2':'value2'}; del d['key2'] ==> d={'key1': 'value1'} #删除键为k的项
d={'key1':'value1','key2':'value2'}; 'key1' in d ==> True #检查字典中是否有键k
字典的格式化字符串:
d={'key1':'value1','key2':'value2'}; "%(key1)" % d ?????
字典方法:
d={'key1':'value1','key2':'value2'}; d.clear() ==> d={} # 清除全部项
d={'key1':'value1','key2':'value2'}; d.copy() # 复制
from copy import deepcopy; d={'key1':'value1','key2':'value2'}; deepcopy(d) # 深度复制
{}.fromkeys(['key1','key2']) ==> {'key2': None, 'key1': None} #创建字典
d={'key1':'value1','key2':'value2'}; d.get('key1') ==> 'value1' #获得值
d={'key1':'value1','key2':'value2'}; d.has_key('key1') ==> True #是否有该键
d={'key1':'value1','key2':'value2'}; d.items() ==> [('key2', 'value2'), ('key1', 'value1')] # 全部项
d={'key1':'value1','key2':'value2'}; d.iteritems() # 迭代全部项
d={'key1':'value1','key2':'value2'}; d.keys() ==> ['key2', 'key1'] #全部键
d={'key1':'value1','key2':'value2'}; d.iterkeys() #迭代全部键
d={'key1':'value1','key2':'value2'}; d.pop('key1') ==>'value1', d={'key2': 'value2'} #移除并pop key1
d={'key1':'value1','key2':'value2'}; d.popitem() ==> ('key2', 'value2'), d={'key1': 'value1'} #移除并pop?
d={'key1':'value1','key2':'value2'}; d.setdefault('key1','defaultValue1') ==> 'value1' #类似于get,如果没有则设置缺省值
d={'key1':'value1','key2':'value2'}; x={'key2':'UPDATE'}; d.update(x) ==> d={'key2': 'UPDATE', 'key1': 'value1'} #用一个字典更新另一个字典
d={'key1':'value1','key2':'value2'}; d.values() ==> ['value2', 'value1'] #全部值
d={'key1':'value1','key2':'value2'}; d.itervalues() # 迭代全部值
len(d) #字典元素个数/长度
遍历字典:
#!/usr/bin/python
dict={"a":"apple","b":"banana","o":"orange"}
print "##########dict######################"
for i in dict:
print "dict[%s]=" % i,dict[i]
print "###########items#####################"
for (k,v) in dict.items():
print "dict[%s]=" % k,v
print "###########iteritems#################"
for k,v in dict.iteritems():
print "dict[%s]=" % k,v
print "###########iterkeys,itervalues#######"
for k,v in zip(dict.iterkeys(),dict.itervalues()):
print "dict[%s]=" % k,v
来源:https://www.cnblogs.com/emanlee/p/4027621.html