Dictionary of normal operation

Disclaimer: # dictionary is a variable type: where the key immutable, value variable format key: value

"" "
1 priority master
1, in accordance with the key: value mapping relationship value (can be kept desirable)
2, members of the operation in, not in # the default judgment Key
3, len () # Get the current key-value pairs in a dictionary the number of
"" "

1. # dictionary definition of three ways

= {D1 ' name ' : ' Egon ' , ' Age ' : 2 }
 Print (D1)
 # The second embodiment: dict () 
D1 = dict (name = ' Sean ' , Age =. 1 )
 Print (type (D1) )
 # third way: zip Learn 
L1 = [ ' name ' , ' Egon ' ]
l2 = ['age',2]
z1 = zip(l1,l2)
print(z1)
print(dict(z1))

2. Dictionary additions and deletions take

 
 
d1 = {'name':'egon','age':2,'hopy':'ee'}
# Operation by 
D1 [ '' weight] = 178
# puncturing operation with a list Remove
del completely remove
d1.clear () to clear the data dictionary
# D1.pop () pop ( 'key ') to delete the specified key, the return value is the key value 
# d1.popitem () Returns the value of the random delete the key is a tuple

#
Fetch operation D1 = { ' name ' : ' Egon ' , ' Age ' : 2, ' HopY ' : ' EE ' } Print (D1 [ ' name ' ])
# d1.get ()
print(d1.get('name','age')
# Change operation 
D1 [ ' Age ' ] = 73 is
 Print (D1)
Change #update present new cover absence 
d1.update ({ 'name': 'Nezha'})
Print (D1)
d1.update ({ 'Sex': 'MALE'})
Print (D1)
# Setdefault: Note the difference between the update key does not exist new key-value pairs, return the new value, key corresponding to the presence of return value 
Print (d1.setdefault ( 'Sex', 'FEMALE'))
# in  not in
print('name' in d1)
Keys #, values, items ****** 
Print (d1.keys ()) # returns all Key
Print (of the type (d1.keys ())) # type 'dict_keys'
Print (d1.values ()) # return all value
Print (d1.items ()) returns all of the # key-value pairs, set the return value is a list of tuples, each key tuple pair present in
for key in d1.keys():
print(key)
for value in d1.values():
print(value)
for key,value in d1.items():
print(key,value)
# Fromkeys: the production of a new dictionary, the first parameter (list), it will first argument of each element of key, the second parameter value to form a new dictionary 
print (dict.fromkeys ([1, 2,3], [ 'k1', 'k2']))

 

Guess you like

Origin www.cnblogs.com/bigbox/p/11809645.html