d = dict() d = dict(name="nico", age=23) d = dict((['name', "nico"], ['age', 23])) d = {} d = {"name":"nico", "age":23}
d = {"name":"nico", "age":23} for key in d: print "key=%s, value=%s" % (key, d[key]) for key in d.iterkeys(): print "key=%s, value=%s" % (key, d[key]) for key in d.keys(): print "key=%s, value=%s" % (key, d[key]) for key in iter(d): print "key=%s, value=%s" % (key, d[key]) for key,item in d.items(): print "key=%s, value=%s" % (key, item)
d = {"name":"nico", "age":23} for value in d.values(): print value for key,value in d.viewitems(): print "key=%s, value=%s" % (key, value) for value in d.viewvalues(): print "value=%s" % (value) #這裏values和viewvalues的區別 #後者返回的是該字典的一個view對象,相似數據庫中的view,當dict改變時,該view對象也跟着改變
rint d["name"] #nico print d.get("name") #nico #若是key不在dict中,返回default,沒有爲None
d = {"name":"nico", "age":23} for key in sorted(d): print "key=%s, value=%s" % (key, d[key]) #key=age, value=23 #key=name, value=nico
3.3 刪除delpython
d = {"name":"nico", "age":23} Python代碼 del d["name"] #若是key不在dict中,拋出KeyError del d["names"] Python代碼 Traceback (most recent call last): File "F:\workspace\project\pydev\src\ddd\ddddd.py", line 64, in <module> del d["names"] KeyError: 'names'
d = {"name":"nico", "age":23} d.clear() print d
3.5 copy數據庫
d1 = d.copy() #{'age': 23, 'name': 'nico'} #使用返回view對象 d2 = d1.viewitems() #dict_items([('age', 23), ('name', 'nico')]) #修改字典d1,新增元素 d1["cc"] = "aaaaaa" print d2 #dict_items([('cc', 'aaaaaa'), ('age', 23), ('name', 'nico')])
#若是key在dict中,返回,不在返回default #若是key在dict中,返回,不在返回default print d.pop("name", "niccco") #nico print d.pop("namezzz", "niccco") #niccco #key不在dict中,且default值也沒有,拋出KeyError print d.pop("namezzz") #此處拋出KeyError
#刪除並返回dict中任意的一個(key,value)隊,若是字典爲空會拋出KeyError d = {"name":"nico", "age":23} print d.popitem() #('age', 23) print d.popitem() #('name', 'nico') #此時字典d已爲空 print d.popitem() #此處會拋出KeyError
#將字典other中的元素加到dict中,key重複時將用other中的值覆蓋 d = {"name":"nico", "age":23} d2 = {"name":"jack", "abcd":123} d.update(d2) print d #{'abcd': 123, 'age': 23, 'name': 'jack'}