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 删除del
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'}