python-字典学习笔记
2016-02-20 20:26
726 查看
# -*- coding: utf-8 -*- #字典:key不能重复 。value可重复。键值对,多个键值对用逗号来分隔 a = {"key" : "value"} person = {"name" : "scb" , "city" : "hainan"} print person #创建空字典 b = {} print type(b) #给空字典加元素 b["name"] = "scb" #有相应的键值对则进行修改,没有则建立一个键值对 b["age"] = 18 print b.setdefault("city", "hn") #有相应的键值对则进行返回, # 没有则建立一个键值对,没有第二个参数则默认为none print b.setdefault("born") print b.setdefault("age") print b #取元素 print b["age"] #不存在会报错 print b.get("age") print b.get("id") #没有相应的键值对,返回null #修改值 b["age"] = 19 print b #删除键值对 del b["age"] print b #key in b print "age" in b #利用dict创建字典 tuple1 = (["name", "scb"] , ["age", 18]) c = dict(tuple1) print c d = dict(name = "scb" , age = 18) print d #fromkeys e = {}.fromkeys(("name" , "name1"),"scb") print e #字典无顺序,无法切片 tuple1 = (["name", "scb"] , ["age", 18]) dict1 = dict(tuple1) #字符串的格式化输出 print "my name is %(name)s" %dict1 + " aged %(age)s" %dict1 print len(dict1) #输出键值对的对数 #字典的常用方法 #print dir(dict) #print help(dict.copy) #copy :浅拷贝:整个字典为新建,但其中内容拷贝时不新建 d = dict(name = "scb" , age = 18) e = d.copy() print id(d) print id(e) d = dict(name = "scb" , hobby = ["read", "play", "eat"]) e = d.copy() d["hobby"].remove("read") #e的字典中也删掉"read" print d print e #深拷贝 deepcode() d = dict(name = "scb" , hobby = ["read", "play", "eat"]) import copy e = copy.deepcopy(d) d["hobby"].remove("read") #e的字典没有删掉"read" print d print e #清除字典中所有键值对 clear() #删除字典 del e #items() 返回一个字典,元素为键值对形成的元组 其迭代器方法iteritems d = dict(name = "scb" , age = 18) print d.items() #keys() 其迭代器方法 has_key() print d.keys() print d.has_key("age") #values()iterkeys其迭代器方法itervalues print d.values() #pop() 删除方法 d = dict(name = "scb" , age = 18) print d.pop("name") print d #update() d1 = {"name" : "scb"} d2 = {"age" : 18} d1.update(d2) print d1
相关文章推荐
- python-元组学习笔记
- 【Python环境】如何使用正确的姿势进行高效Python函数式编程?
- python中变量命名
- Python的一些常用高级函数
- BeautifulSoup4 UserWarning
- python 中 lambda的一些tips
- MonkeyRunner Python环境搭建
- python-opencv图像基本读取函数
- [Python]list, tuple, dict的区别
- Saltstack 报错 python-crypto randomPool_DeprecationWarning:
- KNN
- Python笔记之面向对象
- vim+python+OpenCV学习一 : 图像显示
- python 解析xml包使用方法总结
- 用python写一个简单的爬虫功能
- 类的使用与未知对象的解析--python笔记--廖雪峰站学习笔记(三)
- python 3 系统文本语音朗读api
- python中文件变化监控-watchdog
- Python——类代码编写细节
- python 入门之 长字符串、原始字符串和unicode