dic (dictionary)
Is a key-value dictionary of the type of data stored, the form: { 'name': 'Bob'}. No order in the low version, version 3.6 or more sequential.
Dictionary key must be immutable data types (such as strings, numbers), may be any type of value.
# Define and outputs a dictionary DIC = { ' name ' : ' Bob ' , ' Age ' : 20 is , ' height ' : 180 [ , ' Sex ' : ' MALE ' } Print (DIC)
Dictionary common operation method
Increase of dictionary elements
- A dictionary name [ 'to increase the element name'] = "value of the element to be added, such as dic [" name "] = 'Bob'
- With setdefault () method, if the element does not exist, create
= DIC { ' name ' : ' Bob ' , ' Age ' : 20 is , ' Sex ' : ' MALE ' } DIC [ ' height ' ] = 180 [ # weight element does not exist, creating a new element dic.setdefault ( " weight " 123) # calls setdefault method of adding elements to Print (dic)
Delete dictionary elements
- pop () method, in accordance with the delete key elements, you can set parameters to avoid being given element can not be found
- popitem (), delete a random element in the old version, there are 3.6 or higher in order dictionary, delete the last element
- del dic [ "key"] delete key element in the manner of. del dic delete an entire dictionary
- clear () empty dictionary
dic={ 'name':'小明', 'age':20, 'sex':'male', "weight":123, 1:2 } dic.pop('name',None) dic.popitem() del dic['weight'] # dic.clear() # del dic print(dic)
Change the elements in the dictionary
- The copy operation again by means of the key
- dic1.update (dic2) Method j DIC2 the elements added to dic1, if dic1 already present in the element changes its value, there is added
dic1={ 'name':'小明', 'age':20, 'sex':'male', "weight":123, 1:2 } dic2={'name':'小明','height':180} dic1.update(dic2) print(dic1)
Find the elements in the dictionary
- dic.keys () Gets save all keys to the list
- dic.values () Gets all the values stored as a list
- dic.items () Gets all key-value pairs in the form of tuples stored in the list
dic={ 'name':'小明', 'age':20, 'sex':'male', "weight":123, 1:2 } print(dic.keys()) print(dic.values()) print(dic.items())
With a loop through the dictionary for get it is key
dic={ 'name':'小明', 'age':20, 'sex':'male', "weight":123, 1:2 } for i in dic: print(i)