1 #!/user/bin/env python 2 # -*- coding:utf-8 -*- 3 import copy 4 a = {'zy': 123} 5 6 # clear 7 a.clear() 8 print(a) 9 10 # copy,返回浅拷贝 11 b = {'zy': {'school': 'hx'}} 12 new_dict = b.copy() 13 new_dict['zy']['school'] = 'hx1' 14 print(b) 15 16 # 深拷贝 17 c = {'zy': {'school': 'hx'}} 18 new_dict = copy.deepcopy(c) 19 new_dict['zy']['school'] = 'hx1' 20 print(c) 21 22 # fromkeys 23 new_list = ['zy1', 'zy2'] 24 # fromkeys,第一个参数是一个可迭代对象,第二个参数是value的默认值 25 new_dict = dict.fromkeys(new_list, {'school': 'hx'}) 26 print(new_dict) 27 28 # get 29 value = new_dict.get('zy', None) 30 print(value) 31 32 # item 33 for key, value in new_dict.items(): 34 print(key, value) 35 36 # setdefault, 在get的基础之上,如果在dict中没有get到值,那么不仅仅返回设置的默认值,还会将这个key,value加入到dict中 37 value = new_dict.setdefault('zy', None) 38 print(value) 39 print(new_dict) 40 41 # update,将key,value插入到dict中 42 new_dict.update({'zy111': 111}) 43 new_dict.update(zy222=222, zy333=333) 44 new_dict.update([('zy444','444')]) 45 new_dict.update((('zy555','555'),)) 46 print(new_dict)
{} {'zy': {'school': 'hx1'}} {'zy': {'school': 'hx'}} {'zy1': {'school': 'hx'}, 'zy2': {'school': 'hx'}} None zy1 {'school': 'hx'} zy2 {'school': 'hx'} None {'zy1': {'school': 'hx'}, 'zy2': {'school': 'hx'}, 'zy': None} {'zy1': {'school': 'hx'}, 'zy2': {'school': 'hx'}, 'zy': None, 'zy111': 111, 'zy222': 222, 'zy333': 333, 'zy444': '444', 'zy555': '555'}