python data type (dictionary) VII

Dictionary belonging to sequence type variable that holds the content of which is "key to the form" of storage. Key may be an integer, a string or tuples immutable data types , value can be any data type .

(A) create a dictionary

(1) braces syntax to create dictionary

Code:

= {A ' Tom ' : 20 is, (20 is, 30): ' haha ' , 33 is: [ ' you ' , ' good ' , ' ah ' ]}
 Print (A)

result:

{ 'Tom': 20, (20, 30): 'haha', 33: [ 'you', 'good', 'ah']}

 

(2) () to create a dictionary mapping function by dict

Code:

key = ['','','']
values = [1,2,3]
a = dict(zip(key,values))
print(a)

result:

{ 'A': 1, 'two': 2, 'three': 3}

  

Basic Operation (b) dictionary

(1) Access and delete dictionaries and additions and deletions of key-value pairs

Code:

= {A ' you ' : 250, ' I ' : ' small cute ' , ' haha ' : 234, ' Hello ' : ' small two goods ' }
 # to access the dictionary 
Print (A [ ' you ' ])
 # del delete Dictionary 
# del (A) 
# increasing key value of 
A [ ' One ' ] =. 1
 Print (A)
 # again increased value pairs 
A [ ' TWO '] = 2
print(a)
# Delete key-value pairs 
del A [ ' haha ' ]
 Print (A)
 # modify key-value pair 
A [ ' you ' ] = ' or 250 ' 
Print (A)

result:

250 
{ 'you': 250, 'I': 'Little cute', 'haha': 234, ' Hello': 'small two goods', 'One': 1} 
{ 'you': 250, 'I' : 'small cute', 'haha': 234, ' Hello': 'small two goods', 'One':. 1, 'TWO': 2} 
{ 'you': 250, 'I': 'small cute' 'Hello': 'small two goods',' One ': 1,' TWO ': 2} 
{' you ':' or 250 ',' I ':' little cute ',' hello ':' small two goods', 'one': 1, 'two': 2}

  

The presence or absence of the given key (2) determination dictionary

Code:

= {a ' you ' : 250, ' I ' : ' small cute ' , ' haha ' : 234, ' Hello ' : ' Small two goods ' }
 # determines whether to include as a' you 'of Key 
Print ( ' you '  in a) # True 
# ' Key determine whether to include a name as' he 
Print ( ' he '  in a) # False

result:

True
False

 

(3) keys (), values ​​() and items () method

Code:

= {A ' you ' : 250, ' I ' : ' small cute ' , ' Hello ' : ' Small two goods ' }
 for Key in   a.keys ():
     Print (Key, End = '      ' )
 Print ( ' \ n- ' )
 for values in a.values ():
     Print (values, End = '   ' )
 Print ( ' \ n- ' )
 for Key,values in a.items():
    print("key:",key,'value:',values)

result:

You and I Hello      

250 small cute little two goods   

key: You value: 250 
key: I value: small cute 
key: Hello value: small two goods

  

(4) update () method

update () method using a key-value dictionary of the dictionary contains some already updated.

Code:

= {A ' you ' : 250, ' I ' : ' small cute ' , ' Hello ' : ' Small two goods ' } 
a.update ({ ' you ' : 1, ' I ' : 1 })
 Print (A )

result:

{ 'You': 1, 'I': 1, 'hello': 'small two goods'}

  

 

Guess you like

Origin www.cnblogs.com/abcd8833774477/p/11788719.html