字典的添加、删除、修改操作###
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"} //创建字典
dict["w"] = "watermelon" //添加
del(dict["a"]) //删除
dict["g"] = "grapefruit"
print dict.pop("b")//移除指定键的值
dict.clear()//清空字典 原地操作 注意如果使用dict = dict()会创建一个新字典之前的字典空间不一定释放 可能引起内存溢出
字典的遍历###
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for k in dict:
print "dict[%s] =" % k,dict[k]
//字典items()的使用,每个元素是一个key和value组成的元组,以列表的方式输出print dict.items()
//调用items()实现字典的遍历
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for (k, v) in dict.items():
print "dict[%s] =" % k, v
print dict.keys()//输出key的列表
print dict.values() //输出value的列表
字典的更新####
dict.update(dict2)
//udpate()的等价语句
D = {"key1" : "value1", "key2" : "value2"}
E = {"key3" : "value3", "key4" : "value4"}
for k in E:
D[k] = E[k]print D
设置默认值###
dict.setdefault("a","default")//如字典中存在关键字a则返回a对应的value否则返回default值
按照key排序###
sorted(dict.items(), key=lambda d: d[0], reverse=True)
按照value排序###
sorted(dict.items(), key=lambda d: d[1], reverse=False)
字典的浅拷贝###
dict = {"a" : "apple", "b" : "grape"}
dict2 = {"c" : "orange", "d" : "banana"}
dict2 = dict.copy()
print dict2
字典的深拷贝###
import copy
dict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}}
dict2 = copy.deepcopy(dict)//深拷贝会讲字典的内部对象复制到一个新空间
dict3 = copy.copy(dict)//浅拷贝只会把字典表层的对象拷贝到新空间
dict2["b"]["g"] = "orange"
print dict
dict3["b"]["g"] = "orange"
print dict
网友评论