Python中dict详解
本文内容纲要:
python3.0以上,print函数应为print(),不存在dict.iteritems()这个函数。
在python中写中文注释会报错,这时只要在头部加上#coding=gbk即可
#字典的添加、删除、修改操作
dict={"a":"apple","b":"banana","g":"grape","o":"orange"}
dict["w"]="watermelon"
del(dict["a"])
dict["g"]="grapefruit"
printdict.pop("b")
printdict
dict.clear()
printdict
#字典的遍历
dict={"a":"apple","b":"banana","g":"grape","o":"orange"}
forkindict:
print"dict[%s]="%k,dict[k]
#字典items()的使用
dict={"a":"apple","b":"banana","c":"grape","d":"orange"}
#每个元素是一个key和value组成的元组,以列表的方式输出
printdict.items()
#调用items()实现字典的遍历
dict={"a":"apple","b":"banana","g":"grape","o":"orange"}
for(k,v)indict.items():
print"dict[%s]="%k,v
#调用iteritems()实现字典的遍历
dict={"a":"apple","b":"banana","c":"grape","d":"orange"}
printdict.iteritems()
fork,vindict.iteritems():
print"dict[%s]="%k,v
for(k,v)inzip(dict.iterkeys(),dict.itervalues()):
print"dict[%s]="%k,v
#使用列表、字典作为字典的值
dict={"a":("apple",),"bo":{"b":"banana","o":"orange"},"g":["grape","grapefruit"]}
printdict["a"]
printdict["a"][0]
printdict["bo"]
printdict["bo"]["o"]
printdict["g"]
printdict["g"][1]
dict={"a":"apple","b":"banana","c":"grape","d":"orange"}
#输出key的列表
printdict.keys()
#输出value的列表
printdict.values()
#每个元素是一个key和value组成的元组,以列表的方式输出
printdict.items()
dict={"a":"apple","b":"banana","c":"grape","d":"orange"}
it=dict.iteritems()
printit
#字典中元素的获取方法
dict={"a":"apple","b":"banana","c":"grape","d":"orange"}
printdict
printdict.get("c","apple")
printdict.get("e","apple")
#get()的等价语句
D={"key1":"value1","key2":"value2"}
if"key1"inD:
printD["key1"]
else:
print"None"
#字典的更新
dict={"a":"apple","b":"banana"}
printdict
dict2={"c":"grape","d":"orange"}
dict.update(dict2)
printdict
#udpate()的等价语句
D={"key1":"value1","key2":"value2"}
E={"key3":"value3","key4":"value4"}
forkinE:
D[k]=E[k]
printD
#字典E中含有字典D中的key
D={"key1":"value1","key2":"value2"}
E={"key2":"value3","key4":"value4"}
forkinE:
D[k]=E[k]
printD
#设置默认值
dict={}
dict.setdefault("a")
printdict
dict["a"]="apple"
dict.setdefault("a","default")
printdict
#调用sorted()排序
dict={"a":"apple","b":"grape","c":"orange","d":"banana"}
printdict
#按照key排序
printsorted(dict.items(),key=lambdad:d[0])
#按照value排序
printsorted(dict.items(),key=lambdad:d[1])
#字典的浅拷贝
dict={"a":"apple","b":"grape"}
dict2={"c":"orange","d":"banana"}
dict2=dict.copy()
printdict2
#字典的深拷贝
importcopy
dict={"a":"apple","b":{"g":"grape","o":"orange"}}
dict2=copy.deepcopy(dict)
dict3=copy.copy(dict)
dict2["b"]["g"]="orange"
printdict
dict3["b"]["g"]="orange"
printdict
补充:
1初始化
d=dict(name='visaya',age=20)
d=dict(zip(['name','age'],['visaya',20]))
#dict.fromkeys(listkeys,default=0)把listkeys中的元素作为key均赋值为value,默认为0
d=dict.fromkeys(['a','b'],1)
d
{'a':1,'b':1}
2字典视图和几何
dict.keys()类似信使可以进行交集和并集等集合操作(类似集合,因为不存在重复的项),但dict.values()不可以进行如上操作。
k=d.keys()
k
dict_keys(['a','b'])
list(k)
['a','b']
k|{'x':3}
{'a','x','b'}
k|{'x'}
{'a','x','b'}
k|{'x','y'}
{'a','y','b','x'}
k&{'x'}
set()
v=d.values()
v
dict_values([1,2])
v|{'x'}
Traceback(mostrecentcalllast):
File"",line1,in
TypeError:unsupportedoperandtype(s)for|:'dict_values'and'set'
3排序字典键
两种方法:
3.1sort:
Ks=list(d.keys())
Ks.sort()
forkinKs:
...print(k,d[k])
...
a1
b2
3.2sorted:
forkinsorted(d.keys()):
...print(k,d[k])
...
a1
b2
3.3注意
forkinlist(d.keys()).sort():
...print(k,d[k])
...
Traceback(mostrecentcalllast):
File"",line1,in
TypeError:'NoneType'objectisnotiterable
出错原因:
list.sort()list.append()函数都是对自身的操作,没有返回值,故需先将list(d.keys())的结果保存下来,在结果上进行sort()
4常用函数
4.1get()
D.get(k[,d])=>D[k]ifkinDelsed.ddefaultstonone.
4.2pop()
D.pop(value[,d])=>Removespecifiedkeyandreturnthecorrespondingvalue.Ifkeyisnotfound,disreturnedifgiven,otherwiseKeyErrorisraised.
4.3udpate()
D.update(E,**F)->None.UpdateDfromdict/iterableEandF.
IfEhasa.keys()method,does:forkinE:D[k]=E[k]
IfElacks.keys()method,does:for(k,v)inE:D[k]=v
Ineithercase,thisisfollowedby:forkinF:D[k]=F[k]
d=dict(name='visaya',age=21)
d1={'age':20,'sex':'male'}
d2=zip(['a','b'],[1,2])
d.update(d1)
d
{'age':20,'name':'visaya','sex':'male'}
#forkind1:d[k]=d1[k]
d.update(d2)
d
{'age':20,'name':'visaya','sex':'male'}
#for(k,v)ind2:d[k]=v
4.4del()
delD[key]
4.5clear()
4.6copy()
Python中的dict
初始化
构造方法创建
Python代码
d=dict()
d=dict(name="nico",age=23)
d=dict((['name',"nico"],['age',23]))
当然还有更方便,简单的
Python代码
d={}
d={"name":"nico","age":23}
遍历
通过对key的遍历,遍历整个dict
Python代码
d={"name":"nico","age":23}
forkeyind:
print"key=%s,value=%s"%(key,d[key])
forkeyind.iterkeys():
print"key=%s,value=%s"%(key,d[key])
forkeyind.keys():
print"key=%s,value=%s"%(key,d[key])
forkeyiniter(d):
print"key=%s,value=%s"%(key,d[key])
forkey,itemind.items():
print"key=%s,value=%s"%(key,item)
当然也可以直接遍历value
Python代码
d={"name":"nico","age":23}
forvalueind.values():
printvalue
forkey,valueind.viewitems():
print"key=%s,value=%s"%(key,value)
forvalueind.viewvalues():
print"value=%s"%(value)
这里values和viewvalues的区别
后者返回的是该字典的一个view对象,类似数据库中的view,当dict改变时,该view对象也跟着改变
常用方法
Python代码
d={"name":"nico","age":23}
d["name"]="aaaa"
d["address"]="abcdefg...."
printd#{'age':23,'name':'aaaa','address':'abcdefg....'}
获取dict值
Python代码
printd["name"]#nico
printd.get("name")#nico
如果key不在dict中,返回default,没有为None
Python代码
printd.get("namex","aaa")#aaa
printd.get("namex")#None
排序sorted()
Python代码
d={"name":"nico","age":23}
forkeyinsorted(d):
print"key=%s,value=%s"%(key,d[key])
#key=age,value=23
#key=name,value=nico
删除del
Python代码
d={"name":"nico","age":23}
Python代码
deld["name"]
#如果key不在dict中,抛出KeyError
deld["names"]
Python代码
Traceback(mostrecentcalllast):
File"F:\workspace\project\pydev\src\ddd\ddddd.py",line64,in
deld["names"]
KeyError:'names'
清空clear()
Python代码
d={"name":"nico","age":23}
d.clear()
printd#{}
copy()
Python代码
d1=d.copy()#{'age':23,'name':'nico'}
#使用返回view对象
d2=d1.viewitems()#dict_items([('age',23),('name','nico')])
#修改字典d1,新增元素
d1["cc"]="aaaaaa"
printd2
#dict_items([('cc','aaaaaa'),('age',23),('name','nico')])
pop(key[,default])
如果key在dict中,返回,不在返回default
Python代码
#如果key在dict中,返回,不在返回default
printd.pop("name","niccco")#nico
printd.pop("namezzz","niccco")#niccco
#key不在dict中,且default值也没有,抛出KeyError
printd.pop("namezzz")#此处抛出KeyError
popitem()
删除并返回dict中任意的一个(key,value)队,如果字典为空会抛出KeyError
Python代码
d={"name":"nico","age":23}
printd.popitem()#('age',23)
printd.popitem()#('name','nico')
#此时字典d已为空
printd.popitem()#此处会抛出KeyError
update([other])
将字典other中的元素加到dict中,key重复时将用other中的值覆盖
Python代码
d={"name":"nico","age":23}
d2={"name":"jack","abcd":123}
d.update(d2)
printd#{'abcd':123,'age':23,'name':'jack'}
原文出处:http://blog.csdn.net/tianmo2010/article/details/7621424
本文内容总结:
原文链接:https://www.cnblogs.com/yangyongzhi/archive/2012/09/17/2688326.html