python-字典学习笔记

来源:互联网 发布:股票数据统计软件 编辑:程序博客网 时间:2024/05/16 08:28
# -*- coding: utf-8 -*-#字典:key不能重复 。value可重复。键值对,多个键值对用逗号来分隔a = {"key" : "value"}person = {"name" : "scb" , "city" : "hainan"}print person#创建空字典b = {}print type(b)#给空字典加元素b["name"] = "scb" #有相应的键值对则进行修改,没有则建立一个键值对b["age"] = 18print b.setdefault("city", "hn")  #有相应的键值对则进行返回,# 没有则建立一个键值对,没有第二个参数则默认为noneprint b.setdefault("born")print b.setdefault("age")print b#取元素print b["age"] #不存在会报错print b.get("age")print b.get("id") #没有相应的键值对,返回null#修改值b["age"] = 19print b#删除键值对del b["age"]print b#key in bprint "age" in b#利用dict创建字典tuple1 = (["name", "scb"] , ["age", 18])c = dict(tuple1)print cd = dict(name = "scb" , age = 18)print d#fromkeyse = {}.fromkeys(("name" , "name1"),"scb")print e#字典无顺序,无法切片tuple1 = (["name", "scb"] , ["age", 18])dict1 = dict(tuple1)#字符串的格式化输出print "my name is %(name)s" %dict1 + " aged %(age)s" %dict1print 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 dprint e#深拷贝 deepcode()d = dict(name = "scb" , hobby = ["read", "play", "eat"])import copye = copy.deepcopy(d)d["hobby"].remove("read") #e的字典没有删掉"read"print dprint e#清除字典中所有键值对 clear()#删除字典del e#items() 返回一个字典,元素为键值对形成的元组 其迭代器方法iteritemsd = dict(name = "scb" , age = 18)print d.items()#keys() 其迭代器方法   has_key()print d.keys()print d.has_key("age")#values()iterkeys其迭代器方法itervaluesprint 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
0 0
原创粉丝点击