初始化
构造方法创建
d = dict() d = dict(name="nico", age=23) d = dict((['name', "nico"], ['age', 23]))
当然还有更方便,简单的
d = {} d = {"name":"nico", "age":23}
遍历
通过对key的遍历,遍历整个dict
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)
当然也可以直接遍历value
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对象也跟着改变
常用方法
d = {"name":"nico", "age":23} d["name"] = "aaaa" d["address"] = "abcdefg...." print d #{'age': 23, 'name': 'aaaa', 'address': 'abcdefg....'}
获取dict值
print d["name"] #nico print d.get("name") #nico
如果key不在dict中,返回default,没有为None
print d.get("namex", "aaa") #aaa print d.get("namex") #None
排序sorted()
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
删除del
d = {"name":"nico", "age":23}
del d["name"] #如果key不在dict中,抛出KeyError del d["names"]
Traceback (most recent call last): File "F:\workspace\project\pydev\src\ddd\ddddd.py", line 64, indel d["names"] KeyError: 'names'
清空clear()
d = {"name":"nico", "age":23} d.clear() print d #{}
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')])
pop(key[, default])
如果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
popitem()
删除并返回dict中任意的一个(key,value)队,如果字典为空会抛出KeyError
d = {"name":"nico", "age":23} print d.popitem() #('age', 23) print d.popitem() #('name', 'nico') #此时字典d已为空 print d.popitem() #此处会抛出KeyError
update([other])
将字典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'}