Python dict 详解
来源:互联网 发布:学生党淘宝推荐前十名 编辑:程序博客网 时间:2024/05/16 00:25
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, vfor (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中dict详解
- Python dict 详解
- Python中dict详解
- Python中dict详解
- Python中dict详解
- Python中dict详解
- Python中dict详解
- Python中dict详解
- Python中dict详解
- Python中dict详解
- Python中dict详解
- Python中dict详解
- Python中dict详解
- Python dict详解
- Python中dict详解
- Python中dict详解
- Python中dict详解
- Python中dict详解
- 谷歌Chrome超越IE成全球第一大浏览器
- DEBUG命令 调试 汇编语言程序
- C语言标准库概览详述[7]-变长参数<stdarg.h>
- WingIDE AutoComplete with PySide 的方法
- 中国近代战争
- Python dict 详解
- Simple Undo/redo library for C#/.NET(简单的C#.Net撤销、重做库)
- C语言标准库概览详述[8]-标准IO<stdio.h>
- 算法-判断链表是否有环
- 你若安好
- C语言标准库概览详述[9]-实用函数<stdlib.h>
- C语言标准库概览详述[10]-字符串<string.h>
- need to expert in flieds
- select()