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

Python 字典

时间:2017-06-08 19:43:44      阅读:617      评论:0      收藏:0      [点我收藏+]

标签:cat   auth   bsp   miss   ict   高效   color   pre   iss   

 1 #author F
 2 
 3 #字典基本操作
 4 info = {
 5     stu1101:Mr F,
 6     stu1102:miss l00 ,
 7     stu1103:dr key
 8 }
 9 print(info) #字典是无序的
10 #查询
11 print(info["stu1102"])
12 #修改
13 info["stu1101"] = "aobama"
14 print(info)
15 #增加
16 info["stu1104"] = "Cort"
17 print(info)
18 #删除
19 del info["stu1103"] #删除指定
20 info.pop("stu1102") #删除指定
21 info.popitem() #随便删除
22 #查询
23 dist = {
24     "1":"asd1asd",
25     "2":"asda2sd",
26     "3":"asdas3d",
27     "4":"asd4asd",
28     "5":"as5dasd",
29     "6":"asd6asd",
30     "7":"asda7sd",
31     "8":"asdas8d"
32 }
33 # info[‘9‘] #字典中不存在时报错 KeyError错误
34 print(dist.get("3")) #有就返回 没有返回null
35 print(5 in dist)  #查找字典中是否存在某个key
36 
37 #多级字典嵌套及操作
38 
39 category = {
40     "oumei":{
41         "yourporn":["henduomianfei", "zhiliangyiban"],
42         "pornhub":["henduomianfei", "zhiliangjiaogao"],
43         "letmedothistoyou":["duoshizipai", "ziyuanbuduo"],
44         "x-art":["zhilianghengao", "quanbushoufei"]
45     },
46     "rihan":{
47         "tokyohot":["buzhidao","nizijikan"]
48     },
49     "dalu":{
50         "1024":["quanbumianfei","suduman"]
51     }
52 }
53 category["dalu"]["1024"] = "keyizaiguoneizuojingxiang"
54 category.setdefault("taiwan", {"www.baidu.com":[1,2]}) #先去字典中找 找到则返回 找不到则创建新值
55 
56 print(category)
57 
58 #
59 b = {
60     "teacher1": "1cool",
61     "stu1102": "2cool",
62     "teacher3": "3cool"
63 }
64 info.update(b) #字典合并 有则改 无则加
65 print(info)
66 
67 print(info.items())  #字典转成列表
68 
69 c = dict.fromkeys([6, 7, 8], "test") #初始化一个新的字典
70 print(c) #{6: ‘test‘, 7: ‘test‘, 8: ‘test‘}
71 #
72 c = dict.fromkeys([6, 7, 8], [1, {"name":"aobama"}, 444]) #fromkeys填入的是内存地址 所以导致全部修改
73 c[7][1]["name"] = "changed_name"
74 print(c) #{6: [1, {‘name‘: ‘changed_name‘}, 444], 7: [1, {‘name‘: ‘changed_name‘}, 444], 8: [1, {‘name‘: ‘changed_name‘}, 444]}
75 
76 #字典的循环
77 for i in info: #高效
78     print(i, info[i])
79 
80 for k, v in info.items(): #字典转成列表的过程导致低效
81     print(k, v)

 

Python 字典

标签:cat   auth   bsp   miss   ict   高效   color   pre   iss   

原文地址:http://www.cnblogs.com/fuyuhao/p/6964317.html

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