[5.2] commonly used method of dict

 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 is new_list The = [ ' ZY1 ' , ' ZY2 ' ]
 24  # fromkeys, the first parameter is an iterator object, the second parameter is the default value of 
25 new_dict = dict.fromkeys (new_list The, { ' School ' : ' HX ' })
 26 is  Print (new_dict)
 27  
28  # GET 
29 value = new_dict.get ( ' ZY ' , None)
 30  Print (value)
 31 is  
32  # Item 
33 is  for Key, value innew_dict.items ():
 34      Print (key, value)
 35  
36  # setDefault, on the basis of get on top, if not get the value in dict, then just return to set default values, but also to the key, value dict added to the 
37 [ value = new_dict.setdefault ( ' ZY ' , None)
 38 is  Print (value)
 39  Print (new_dict)
 40  
41 is  # Update, the key, value inserted into the dict 
42 is new_dict.update ({ ' zy111 ' : 111 })
 43 is new_dict.update (zy222 = 222, 333 = zy333 )
 44 is 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'}

  

Guess you like

Origin www.cnblogs.com/zydeboke/p/11250499.html