1、clear:删除所有元素
#D.clear() -> None. Remove all items from D
dic_a ={:'kong',:'zha',:'gen'}
dic_a.clear()
print(dic_a)
结果:{}
2、fromkeys():从序列键和值生成字典的key,value来构建一个新字典
#dict.fromkeys(seq[, value]))
seq:是为字典的键准备的
value:是字典的默认值 seq = ('Name','Age','Sex')
new_dic = dict.fromkeys(seq,)
print(new_dic)
结果:{'Age': , 'Sex': , 'Name': }
3、get:获取字典值
#get(self, k, d=None)
如果字典中没有1键,则值返回默认值10,如果不返回默认值,则返回None
dic = {:'kong',:'zha'}
print(dic.get(1,10))
结果:'kong'
4、items:返回一个类集合对象
dic = {:'kong',:'zha'}
print(dic.items())
结果:dict_items([(, 'kong'), (, 'zha')])
5、keys:返回一个类集合对象
dic = {:'kong',:'zha'}
new_dic = dic.keys()
print(new_dic)
for x in new_dic:
print(x)
结果:
dict_keys([, ])
6、pop:删除字典指定的键值,返回一个value值,必须指定键删除
#D.pop(k[,d]) -> v, remove specified key and return the corresponding value
dic = {:'kong',:'zha'}
print(dic.pop())
print(dic)
结果:
kong
{: 'zha'}
7、popitem:随机移除字典的键值对,返回一个元组,如果字典为空则报错
#D.popitem() -> (k, v), remove and return some (key, value) pair as a
-tuple; but raise KeyError if D is empty.
dic = {:'kong',:'zha',:'gen'}
print(dic.popitem())
print(dic)
结果:
(1, 'kong')
{2: 'zha', 3: 'gen'}
8、setdefault:如果键在字典中,返回键对应的值,如果键不在字典中,向字典中插入这个键值
#D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
dic = {:'kong',:'zha',:'gen',:'ff',:'pp'}
pp = dic.setdefault(,'ppp')
print(dic)
print(pp)
结果:
{: 'kong', : 'zha', : 'gen', : 'ff', : 'pp', : 'ppp'}
ppp
9、update:用dic2更新dic1:如果dic2的键在dic1中不存在,则dic2插入到dic1,否则更用dic2的键值,更新dic1
dic1 = {'Name':'kong','Age':}
dic2 = {'Name':'Hucli','Sex':'M'}
print(dic1,dic2)
dic1.update(dic2)
print(dic1)
结果:
{'Age': , 'Name': 'kong'} {'Name': 'Hucli', 'Sex': 'M'}
{'Age': , 'Name': 'Hucli', 'Sex': 'M'}
10、values:返回字典的所有值
#D.values() -> an object providing a view on D's values
dic1 = {'Name':'kong','Age':}
print(dic1.values())
结果:dict_values([, 'kong'])
11、汇总
dict1 = {
"Language":"English",
"Title":"Python Book",
"Pages":450
} dict2 = {
"Author":"David",
"Price":33,
"Pages":550 }
print dict1.clear() # 清空字典
dict3 = dict1.copy() # 复制字典
print dict3
seq = ['book','pape']
print dict1.fromkeys(seq) # 以seq中的元素作为键创建字典
print dict1.get('Title') # 读取字典中的键title,无则返回None
print dict1.has_key("Title") # 判断键Title是否在dict1中
tt = dict1.iteritems() # 返回字典中所有键值对的迭代器
for k in tt:
print k
pp = dict1.iterkeys() # 返回字典中所有键的迭代器
for p in pp:
print p
dict1.itervalues() # 反加字典中所有值的迭代器
t1 = dict1.pop("Title") # 读取字典中该键的值并删除该键及值
dict1.update(dict2) # 合并字典
print dict1