Python dict 详解
2012-09-19 18:04
351 查看
mydict = {"server":"local", "database":"master", "uid":"admin", "pwd":"secret"}
dict是无序的
dict 增加元素
mydict[1] = "test" mydict.setdefault(2,"test2")
注意:setdefault只有在该key不存在的情况下才将该key-value插入dict。如果该key已存在,则setdefault不会修改该key对应的valule,也就是说此时setdefault对dict无任何影响。
dict 删除元素
del(mydict[1]) mydict.pop(2) mydict.clear()
dict 查找元素
if "key1" in mydict: print mydict["key1"] else: print "None" mydict.get("key1")
注:get时如果该键不存在返回None,不会报错,如果直接下标取值当该键不存在时会报错。
dict 修改元素
mydict["key1"] = "value1"
dict 字典的遍历
for k in mydict: print "mydict[%s] =" % k,mydict[k] #字典items()的使用 #每个元素是一个key和value组成的元组,以列表的方式输出 for (k, v) in mydict.items(): print "mydict[%s] =" % k, v #调用iteritems()实现字典的遍历 for k, v in mydict.iteritems(): print "mydict[%s] =" % k, v for (k, v) in zip(mydict.iterkeys(), mydict.itervalues()): print "mydict[%s] =" % k, v
#输出key的列表 print mydict.keys() #输出value的列表 print mydict.values()
#字典的更新
dict1 = {"a" : "apple", "b" : "banana"} dict2 = {"b" : "grape", "c" : "orange"} dict1.update(dict2) print dict1 #{'a': 'apple', 'c': 'orange', 'b': 'grape'} print dict2 #{'c': 'orange', 'b': 'grape'}
dict 浅拷贝
dict1 = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}} dict2 = copy.copy(dict1)#或者使用dict1.copy() print dict2 #{"a" : "apple", "b" : {"g" : "grape","o" : "orange"}} dict2["b"]["o"] = "apple2" print dict2 #{"a" : "apple", "b" : {"g" : "grape","o" : "apple2"}} print dict1 #{"a" : "apple", "b" : {"g" : "grape","o" : "apple2"}}
dict 深拷贝
dict1 = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}} dict2 = copy.deepcopy(dict1) print dict2 #{"a" : "apple", "b" : {"g" : "grape","o" : "orange"}} dict2["b"]["o"] = "apple2" print dict2 #{"a" : "apple", "b" : {"g" : "grape","o" : "apple2"}} print dict1 #{"a" : "apple", "b" : {"g" : "grape","o" : "orange"}}
相关文章推荐
- python——Container之字典(dict)详解
- Python中dict详解
- Python中的list/tuple/dict/set数据类型详解(转载)
- 详解Python中dict与set的使用
- Python dict详解
- python -dict 详解
- python中defaultdict的用法详解
- Python中dict详解
- python中defaultdict的用法详解
- 详解python中的json和字典dict
- Python数据类型详解(四)字典:dict
- Python - 字典(dict) 详解 及 代码
- Python中的list/tuple/dict/set数据类型详解
- python字典DICT类型合并详解
- Python中dict详解
- Python - 字典(dict) 详解 及 代码
- Python中字典(dict)详解
- Python中dict详解
- python的dict,set,list,tuple应用详解
- python dict.get()和dict['key']的区别详解