06-1 数据类型—dict
字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。
python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,key是唯一的,且key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、元组。
字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别还在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
一、创建字典
dic2 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
dic = dict((('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')))
创建时如果同一个键被赋值两次,后一个值会覆盖前面的值
二、操作
1、查
dic = {'name': 'alex', 'age': 35, 'class': 'first'}
dic['name'] # 通过键查找。没有此键时,会报错
dic.keys() # 查看字典里所有的键。返回dict_keys(['name', 'age', 'class']),转化成list:list(dic.keys())
dic.values() # 返回dict_values(['alex', 35, 'first'])
dic.items() # 返回dict_items([('name', 'alex'), ('age', 35), ('class', 'first')])
dic.get('school', -1) # key存在,返回相对应的值。如果key不存在,默认返回None,或者自己指定的value(在第二参数上指定)。即key不存在也不会报错。
'name' in dic # 查看dic中是否存在'name'键,若存在返回True
2、增
dic['School'] = "Qinghua"
ret = dic.setdefault('class', 'second') #键存在,不改动键值,且返回相应键值;键不存在,在字典中增加新的键值对,且返回新的新键值对的键值
3、改
dic = {'name': 'jack', 'age': 35, 'class': 'first'}
dic1 = {'Name': 'jack', 'age': 15, 'school': 'Qinghua'}
dic['age'] = 8 # 如果键存在,在改变键的值;如果不存在则新增此键值对
dic.update(dic1) # 用字典dic1的“键/值”对覆盖dict中有相同键名的“键/值”对,若dic不存某“键/值”对,就在dic中新建。
print(dic) # 输入为{'name': 'jack', 'age': 15, 'class': 'first', 'Name': 'jack', 'school': 'Qinghua'}
4、删
del dict['age']; # 删除字典中的指定键值对
dict.clear(); # 清空词典所有条目
del dict ; # 删除词典
dict.pop('class') # 删除字典中指定键值对,且返回value值
dict.popitem() # 随机删除某组键值对,并以元组返回值
三、其他操作及涉及到的方法
1、字典的遍历
for i in dic: # 推荐用这种方法,因为比下面的方法效率高
print(i,dic[i])
for item in dic.items(): # dic.items()可以换成dic.keys()或dic.values()
print(item)
for key ,value in dic.items():
print(key, value)
2、字典的嵌套
1 menu = { 2 '山东': { 3 '济南': { 4 '历下区': { 5 '历下公司1': {}, 6 '历下公司2': {} 7 }, 8 '天桥区': { 9 '天桥公司1':{}, 10 '天桥公司2':{} 11 }, 12 '市中区': { 13 '市中公司1': {}, 14 '市中公司2': {} 15 } 16 }, 17 '德州': { 18 '德城区': { 19 '德城公司1': {} 20 }, 21 '乐陵市': { 22 '乐陵工厂1': {}, 23 '乐陵工厂2': {}, 24 '乐陵工厂3': {} 25 } 26 } 27 }, 28 '山西': { 29 '太原': { 30 '小店区': { 31 '小店公司1': {}, 32 '小店公司2': {} 33 }, 34 '迎泽区': {} 35 } 36 }, 37 '河北': { 38 '石家庄': {} 39 } 40 } 41 42 43 back_flag = False #用于当前循环的终止 44 exit_flag = False #用于控制所有循环的终止 45 46 while not exit_flag and not back_flag: 47 for key in menu: 48 print(key) 49 choice1 = input('1>>>[out:q, back: b]:').strip() 50 if choice1 in menu: 51 while not exit_flag and not back_flag: 52 for key in menu[choice1]: 53 print(key) 54 choice2 = input('2>>>[out:q, back: b]:').strip() 55 if choice2 in menu[choice1]: 56 while not exit_flag and not back_flag : 57 for key in menu[choice1][choice2]: 58 print(key) 59 choice3 = input('3>>>[out:q, back: b]:').strip() 60 if choice3 in menu[choice1][choice2]: 61 while not exit_flag and not back_flag: 62 for key in menu[choice1][choice2][choice3]: 63 print(key) 64 print('this is the last layer!') 65 choice4 = input('4>>>[out:q, back: b]:').strip() 66 if choice4 == 'b': 67 back_flag = True 68 elif choice4 == 'q': 69 exit_flag = True 70 else: 71 back_flag = False #回置为False,避免退出全部循环 72 elif choice3 == 'b': 73 back_flag = True 74 elif choice3 == 'q': 75 exit_flag = True 76 else: 77 print('wrong input!') 78 else: 79 back_flag = False 80 elif choice2 == 'b': 81 back_flag = True 82 elif choice2 == 'q': 83 exit_flag = True 84 else: 85 print('wrong input!') 86 else: 87 back_flag = False 88 elif choice1 == 'b': 89 back_falg = True 90 elif choice1 == 'q': 91 exit_flag = True 92 else: 93 print('wrong input!')
1 menu = { 2 '山东': { 3 '济南': { 4 '历下区': { 5 '历下公司1': {}, 6 '历下公司2': {} 7 }, 8 '天桥区': { 9 '天桥公司1':{}, 10 '天桥公司2':{} 11 }, 12 '市中区': { 13 '市中公司1': {}, 14 '市中公司2': {} 15 } 16 }, 17 '德州': { 18 '德城区': { 19 '德城公司1': {} 20 }, 21 '乐陵市': { 22 '乐陵工厂1': {}, 23 '乐陵工厂2': {}, 24 '乐陵工厂3': {} 25 } 26 } 27 }, 28 '山西': { 29 '太原': { 30 '小店区': { 31 '小店公司1': {}, 32 '小店公司2': {} 33 }, 34 '迎泽区': {} 35 } 36 }, 37 '河北': { 38 '石家庄': {} 39 } 40 } 41 42 choice_list = [] 43 choice_list.append(menu) 44 exit_flag = False 45 46 while not exit_flag: 47 current_menu = choice_list[-1] 48 for key in current_menu: 49 print(key) 50 choice = input("input your choice [out: q,back:b]>>>:").strip() 51 if choice in current_menu: 52 choice_list.append(current_menu[choice]) 53 elif choice == 'q': 54 exit_flag = True 55 elif choice == 'b': 56 choice_list.pop()
1 with open('city.txt', 'r', encoding='utf-8') as f: 2 menu = eval(f.read()) 3 4 choice_list = [] 5 choice_list.append(menu) 6 exit_flag = False 7 8 while not exit_flag: 9 current_menu = choice_list[-1] 10 for key in current_menu: 11 print(key) 12 13 choice = input("input your choice [q/b or e]>>>:").strip() 14 if choice in current_menu: 15 choice_list.append(current_menu[choice]) 16 elif choice == 'q': #退出菜单 17 exit_flag = True 18 elif choice == 'b': #后退 19 choice_list.pop() 20 elif choice == 'e': #修改菜单 21 change = input("'del ***' or 'add ***' >>>:") 22 ret = change.split(' ') 23 if ret[0] == 'del' and ret[1] in current_menu: 24 del current_menu[ret[1]] 25 elif ret[0] == 'add' and ret[1] not in current_menu: 26 current_menu[ret[1]] = {} 27 28 with open('city.txt', 'w', encoding='utf-8') as f: 29 f.write(str(choice_list[0])) #用浅拷贝机制理解
3、dict.fromkeys(seq, val)
创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
d1=dict.fromkeys(['host1','host2','host3'],'Mac')
print(d1) # 输出为{'host1': 'Mac', 'host2': 'Mac', 'host3': 'Mac'}
4.ret = sorted(dic)
返回一个排好序的key的列表
4、len(dict)
计算字典元素个数,即键的总数。
5、dict.copy()
返回一个字典的浅复制
浙公网安备 33010602011771号