Mappings : Relationship of key-value pairs, key (key) mapping values (value)
The dictionary is the only type of mapping for Python
>>> Phonebook = {'Wakey':'1111','Ethon':'2222','Joho':'3333'}>>>phonebook{'Joho':'3333','Wakey':'1111','Ethon':'2222'}
Extension: the difference between a mapping type and a sequence type
1, Access way, sequence type with a numeric type of key, and the mapping type can be used other object type key (General string)
>>> lis = ['a','b','C']>>> lis[2]'C'>>> dic = {'name':'a','Father':'b','Mother':'C'}>>> dic['Mother']'C'
2, the storage type is different, the mapping type key, directly or indirectly is related to the value.
3. Sequence type, ordered column; map type is unordered
Dictionary:
1. dict function
>>> items = [('name','Gumby'),(' Age', 42)]#Create a dictionary from other mappings or key-value pairs>>> d =dict (items)>>>d{' Age': 42,'name':'Gumby'}>>> >>> d = dict (name='Ethon', age=42)#creating a dictionary with keyword parameters>>>d{' Age': 42,'name':'Ethon'}
2. Dictionary Features:
1) The key can be any immutable type (the most powerful place in the dictionary)
2) keys in the dictionary may be added automatically
>>> x = {} # empty dictionary >>> x[2]='ethon'>>> x{'ethon'}
3. Dictionary method
Dict.clear (): Delete all elements in the dictionary
>>> x = {'name':'wakey',' age ' ': >>> x.clear ()>>> x{}
Dict.copy (): Returns a new dictionary with the same key-value pair
>>> x = {'name':'Wakey',' Age': 22}>>> y =x.copy ()>>> y['name']='Ethon'>>>y{' Age': 22,'name':'Ethon'}>>>x{' Age': 22,'name':'Wakey'}
Dict.formkeys (): Create a new dictionary with the given key
>>> {}.fromkeys (['name','age']) {' Age'name': none} # None as default
Dict.get (Key,default=none): Returns the corresponding key value
>>> d = {}print d.get ('name') None # get access to a nonexistent key when you get the None value
Dict.has_key (): Check if key exists
>>> d = {}>>> D.has_key ('name') False>>> d[ ' name '] ='ethon'>>> d.has_key ('name') True
Dict.items (): Returns all dictionary entries as a list, with no specific order of items returned.
>>> d = {'title':'Python web site','URL':'http://www.python.com'}>>>D.items () [('URL','http://www.python.com'), ('title','Python web site')]
Dict.keys (): List of Keys dict.values (): List of values
Dict.pop (): Gets the value corresponding to the given key, and then removes the key-value pair from the dictionary
>>> d = {'x': 1,'y': 2}>>> D.pop ( ' x ' )1>>> d{'y': 2}
Dict.popitem (): The last element of the pop-up list (random popup), this method is useful if you want to remove and manipulate items one by one.
>>> d = {'title':'python','URL':'www.python,com'}>>>D.popitem () ('URL','www.python,com')>>>d{'title':'python'}
Dict.update (): Update another dictionary with one dictionary item
>>> d = {'title':'python','URL':'www.python,com'}>>> x = {'title':'Python language website'}>>>d.update (x)>>>d{'URL':'www.python,com','title':'Python language website'}
Python Basics 6 (dictionary)