码迷,mamicode.com
首页 > 编程语言 > 详细

python---字典

时间:2018-01-25 15:45:01      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:下标   toolbar   tde   dict   输出   python   获取   修改   default   

#字典是key-value的数据类型,字典是无序的,没有下标(列表有下标),key必须是唯一的

info = {
    "stu001":"fengxiaoli",
    "stu002":"cx",
    "stu003":"wyc",
    "stu004":"ljh",
}


###-----------------循环字典
for i in info:              #推荐使用
    print(i,info[i])

for k,v in info.items():    #不推荐,因为它是先转化为列表在打印,数据量的时候数据会很慢
    print(k,v)
    
    
###-----------------查询
print("stu001" in info)     #判断key是否在字典中,同py2中 info.has_key("stu001")
print(info.get("stu002"))   #通过key获取value,推荐使用
print(info["stu001"])
print(info)  
    
    
###-----------------修改
info["stu003"] = "fzl"        #有那个key就修改,没有新增
info["stu005"] = "fzl"
print(info)


###-----------------删除
del info                       #删除整个字典
del info["stu005"]
info.pop("stu004")
info.popitem()                 #随机删除一组


###-----------------合并两个字典
b = {
    "stu001":"fxl",
    3:5,
    4:8,
}
info.update(b)      #合并字典info和字典b,有重复的就更新,不重复的就合并
print(info)


###-----------------把字典转成列表
print(info.items())


###-----------------初始化一个字典
c = dict.fromkeys([7,8,9],"test")
print(c)
#输出{8: 'test', 9: 'test', 7: 'test'}

c1 = dict.fromkeys([7,8,9],{1:"feng",2:"cx",3:"fxl"})
print(c1)
#输出{8: {1: 'feng', 2: 'cx', 3: 'fxl'}, 9: {1: 'feng', 2: 'cx', 3: 'fxl'}, 7: {1: 'feng', 2: 'cx', 3: 'fxl'}}

c1[8][2]="xia"      #类似浅copy,二级字典中数据指向同一内存地址,修改一个所有都改变
print(c1)
#输出{8: {1: 'feng', 2: 'xia', 3: 'fxl'}, 9: {1: 'feng', 2: 'xia', 3: 'fxl'}, 7: {1: 'feng', 2: 'xia', 3: 'fxl'}}
   
   

###-----------------多级字典
info2 = {
    "stu001":{"fxl":["性别:男","年龄:21"]},
    "stu002":{"cx":["性别:女","年龄:25"]},
    "stu003":{"fzl":["性别:男","年龄:35"]},
}
info2["stu001"]["fxl"][1] = "年龄:23"            #修改
info2.setdefault("stu004",{"ljh":["性别:女","年龄:40"]})     #增加,如果字典中有这个key就不改变原值,没有就新建
print(info2)


python---字典

标签:下标   toolbar   tde   dict   输出   python   获取   修改   default   

原文地址:http://blog.51cto.com/fengxiaoli/2065023

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!