您的位置:首页 > 编程语言 > Python开发

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: