Python 字典

字典Dictonary

  • 一种key - value的数据类型
  • 语法
1 info = {
2     'stu1101': "Teng",
3     'stu1102': "Long",
4     'stu1103': "Xiao",
5 }
  • dict是无序的, 没有下标
  • key 必须是唯一的

字典基本操作

 1 # 创建字典
 2 info = {
 3     'stu1101': "Teng",
 4     'stu1102': "Long",
 5     'stu1103': "Xiao",
 6 }
 7 
 8 print(info)
 9 
10 # 查找方法1, 根据指定key查
11 print(info['stu1101']) # 若key不存在,会出错.
12 
13 
14 # 查找方法2, 根据指定key查
15 print(info.get('stu1104')) # 若key不存在,返回null. 案例的查找方法.
16 
17 
18 # 修改方法1, 根据指定key修改对应值
19 info['stu110'] = 'aa'  # 若key存在,则修改
20 info['stu114'] = 'bb'  # 若key不存在,则添加
21 print(info)
22 
23 
24 # 修改方法2,
25 info2 = {
26     'stu1101':'alex', # info中也有这个键,但值和info2不同.
27     1:3,
28     2:5
29 }
30 info.update(info2) # 把两个字典合并. 其中key有交叉的将对应值修改成info2中的值.
31 
32 
33 # 删除方法1, 根据指定key删
34 del info['stu1101']
35 
36 
37 # 删除方法2, 根据指定key删
38 info.pop('stu1101')
39 
40 
41 # 删除方法3: 随机删
42 info.popitem()
43 
44 
45 # 判断key是否存在于字典中
46 print('stu1105' in info)
47 # info.has_key('stu1105) 和print('stu1105' in info)效果一样,不过这个语句只在python2里有. python3已经去掉.
48 
49 
50 # 取出所有的值
51 info.values()
52 
53 
54 # 取出所有的key
55 info.keys()
56 
57 
58 # 另一种方式的添加. 若key在字典中存在,就返回其对应的值; 若key不存在,则添加进字典.
59 info.setdefault('stu1106','alex')
60 
61 
62 # 将字典转换成列表
63 print(info.items())
64 
65 
66 # 初始化一个新的字典, key就是方法中指定的test
67 c = dict.fromkeys([6,7,8],'test')
68 c2 = dict.fromkeys([6,7,8],[1,{"name":"alex"},444]) # 这样写其实是列表[1,{"name":"alex"},444]整体作为新字典c2的key.
69 print(c)
70 
71 
72 
73 # 循环遍历方法1
74 for i in info:
75     print(i,info[i])
76 # 方法1比方法2高效很多.
77 # 循环遍历方法1
78 for k,v  in info.items():
79     print(k,v)

多级字典嵌套

 1 # 多级字典嵌套
 2 catalog = {
 3     '欧美':{
 4         'aaa':['abc','cde'],
 5         'bbb': ['abcfew', 'wdfa'],
 6         'ccc': ['vafew', 'avcaf']
 7     },
 8 
 9     '日韩': {
10         'eee': ['aqza', 'wdd'],
11         'fff': ['bcvd', 'gava'],
12         'ggg': ['gdaw', 'aeve']
13     },
14 
15     '中国': {
16         'hhh': ['bfdsf', 'mgt'],
17         'iii': ['hgfhf', 'ytnb'],
18         'jjj': ['jytjt', 'rhdnb']
19     },
20 }
21 
22 # 修改其中一个内嵌字典的值
23 catalog['中国']['hhh'][1] = 'kkyyllla'

练习: 三级菜单

 1 data={
 2     '北京':{
 3         '昌平': {
 4             '沙河':['oldboy','test'],
 5             '天通苑': ['链家地产','我爱我家']
 6         },
 7 
 8         '朝阳': {
 9             '望京': ['奔驰', '陌陌'],
10             '国贸': ['CICC', 'HP'],
11             '东直门': ['Advent', '飞信'],
12         },
13 
14         '朝阳': {
15             '望京': ['奔驰', '陌陌'],
16             '国贸': ['CICC', 'HP'],
17             '东直门': ['Advent', '飞信'],
18         },
19 
20         '海淀': {
21 
22         },
23     },
24 
25     '山东': {
26         '德州': {},
27         '青岛': {},
28         '济南': {},
29     },
30 
31     '广东': {
32         '东莞': {},
33         '常熟': {},
34         '佛山': {},
35     },
36 }
37 
38 # 循环打印每一级菜单
39 exit_flag = False
40 while not exit_flag:
41     for i in data:
42         print(i)
43 
44     choice = input('去哪? ')
45     if choice in data:
46         while not exit_flag:
47             for i2 in data[choice]:
48                 print("	",i2)
49 
50             choice2 = input('去哪? ')
51             if choice2 in data[choice]:
52                 while not exit_flag:
53                     for i3 in data[choice][choice2]:
54                         print("		",i3)
55                     choice3 = input('去哪? ')
56                     if choice3 in data[choice][choice2][choice3]:
57                         while not exit_flag:
58                             for i4 in data[choice3]:
59                                 print("			",i4)
60 
61                             choice4 = input('最后一层, 按b返回上一层')
62                             if choice4=='b':
63                                 pass # 什么也不做. 一个占位符,防止报错.
64                             elif choice4=='quit':
65                                 exit_flag=True
66                     if choice3 == 'b':
67                          break
68                     elif choice3 == 'quit':
69                         exit_flag = True
70             if choice2 == 'b':
71                 break
72             elif choice2 == 'quit':
73                 exit_flag = True

 优化后代码

 1 menu = {
 2     '北京': {
 3         '昌平': {
 4             '沙河': ['HeiMa', 'test'],
 5             '天通苑': ['链家地产', '我爱我家']
 6         },
 7 
 8         '朝阳': {
 9             '望京': ['奔驰', '陌陌'],
10             '国贸': ['COCO', 'HP'],
11             '东直门': ['Advent', '飞信']
12         },
13         
14         '海淀': {
15             '长安街': ['UNIQUE', 'SINGLE'],
16             '东门街': ['国贸', '东门']
17         },
18     },
19 
20     '山东': {
21         '德州': {
22             '大安': ['人民广场', '黄埔路', '南京东路'],
23             '东建': ['西顶广场', '长河路', '北安路']
24         },
25         '青岛': {
26             '东海': ['创意广场', '文化广场'],
27             '渤海湾': ['创意广场', '文化广场']
28         },
29         '济南': {
30             '南山': ['东门', '北门'],
31             '钟南山': ['南门', '西门']
32         },
33     },
34 
35     '广东': {
36         '东莞': {
37             '金湾': ['APPLE', 'PAD'],
38             '银湾': ['GOLD', 'SLIVER']
39         },
40         '常熟': {
41             '天安': ['PHONE', 'WATCH'],
42             '地安': ['SET', 'INFLATION']
43         },
44         '佛山': {
45             '越秀': ['海洋公园', '湿地公园'],
46             '天河': ['海上公园', '动物乐园']
47         },
48     },
49 }
50 
51 upper_level = []
52 curr_menu = menu
53 while True:
54 
55     # 循环打印每一级菜单
56     for i in curr_menu:
57         print(i)
58 
59     # 用户选择
60     choice = input('去哪? ')
61 
62     if choice == 'back':
63         if len(upper_level) > 0:  # 代表有下一层
64             curr_menu = upper_level.pop()  # 提取upper_level的最后一个元素并删掉(模拟返回上一级菜单结果)
65         else:
66             print('这是最项层')
67         continue
68     elif choice == 'quit':
69         exit(0)
70 
71     if isinstance(curr_menu, dict) :
72         # 如果当前层是字典,还有下一级, 可以继续
73         if choice in curr_menu:
74             upper_level.append(curr_menu)  # 把当前层的引用添加到上级菜单的历史列表
75             curr_menu = curr_menu[choice]
76         else:
77             print('输入有误')
78         continue
79     if isinstance(curr_menu, list):
80         print('这是最后一层')
81         continue
原文地址:https://www.cnblogs.com/cheese320/p/8820700.html