Dictionaries consist of pairs of keys and their corresponding values (which make key-value pairs an item), separated by a colon (:) between each key and its value, separated by commas (,), and the entire dictionary enclosed by a pair of curly braces. An empty dictionary consists of two curly braces: {}
dict function
You can use the Dict function to create a dictionary from a sequence of other mappings or (keys, values)
The code is as follows:
>>> items=[(' name ', ' Gumby '), (' Age ', 42)]
>>> d=dict (items)
>>> D
{' Age ':, ' name ': ' Gumby '}
>>> d[' name ']
' Gumby '
The Dict function can also create a dictionary with keyword parameters:
The code is as follows:
>>> d=dict (name= ' Gumby ', age=42)
>>> D
{' Age ':, ' name ': ' Gumby '}
Basic Dictionary operations:
The basic behavior of a dictionary is similar to a sequence in many ways:
Len (d) Returns the number of items in D (key-value pairs)
D[K] Returns the value associated to the key K
D[K]=V associates the value V to the key K
Del D[k] Delete item with key K
K in D checks if D contains an entry with a key of K
Description
Key type: The key of a dictionary is not necessarily an integral type, or it may be another immutable type
Auto Add: Even if the key start does not exist in the dictionary, you can assign a value to it so that the dictionary creates a new item and cannot associate the value to an index outside the list range
Membership: The expression K in D (d is a dictionary) looks for a key, not a value. The expression V in L (L is a list) is used to look up a value instead of an index
Dictionary method:
1. Clear
The clear method clears all items in the dictionary, which is an in-place operation, so no return value
The code is as follows:
>>> d={}
>>> d[' name ']= ' Gumby '
>>> d[' age ']=42
>>> D
{' Age ':, ' name ': ' Gumby '}
>>> Return_value=d.clear ()
>>> D
{}
>>> Print Return_value
None
Consider the following two scenarios:
The code is as follows:
>>> x={}
>>> y=x
>>> x[' key ']= ' value '
>>> y
{' key ': ' Value '}
>>> x={}
>>> y
{' key ': ' Value '}
>>>
>>> x={}
>>> y=x
>>> x[' key ']= ' value '
>>> y
{' key ': ' Value '}
>>> X.clear ()
>>> y
{}
2. Copy
The Copy method returns a new dictionary with the same key-value pairs (this method implements a shallow copy)
The code is as follows:
>>> x={' username ': ' admin ', ' machines ': [' foo ', ' Bar ', ' Baz ']}
>>> y=x.copy ()
>>> y[' username ']= ' MLH '
>>> y[' machines '].remove (' bar ')
>>> y
{' username ': ' MLH ', ' Machines ': [' foo ', ' Baz ']}
>>> x
{' username ': ' admin ', ' machines ': [' foo ', ' Baz '}}
As you can see from the code above, the original dictionary is not affected when the value is replaced in the copy, but if a value is modified, the original dictionary will also change
One way to avoid this problem is to use deep copy to copy all the values it contains, and you can use the Deepcopy function of the copy module to complete the operation:
The code is as follows:
>>> from copy import deepcopy
>>> d={}
>>> d[' names ']=[' Alfred ', ' Bertrand ']
>>> c=d.copy ()
>>> Dc=deepcopy (d)
>>> d[' names '].append (' Clive ')
>>> C
{' names ': [' Alfred ', ' Bertrand ', ' Clive ']}
>>> DC
{' names ': [' Alfred ', ' Bertrand ']}
3, Fromkeys
The Fromkeys method creates a new dictionary with the given key, and each key defaults to a value of none
The code is as follows:
>>> {}.fromkeys ([' Nmae ', ' age '])
{' Age ': none, ' Nmae ': none}
4. Get
The Get method is a more relaxed way to access a dictionary entry. In general, an error occurs if you try to access an item that does not exist in the dictionary:
The code is as follows:
>>> d={}
>>> print d[' name ']
Traceback (most recent):
File " ", line 1, in
Print d[' name ']
Keyerror: ' Name '
>>> print d.get (' name ')
Using get will not
Example of a simple database using get
The code is as follows:
people={
' Alice ': {
' Phone ': ' 2341 ',
' Add ': ' Foo drive 23 '
},
' Beth ': {
' Phone ': ' 934 ',
' Add ': ' Bar Street 42 '
},
' Cecil ': {
' Phone ': ' 2314 ',
' Add ': ' Baz Avenue 90 '
}
}
labels={
' Phone ': ' Phone number ',
' Addr ': ' Address '
}
Name=raw_input (' Name: ')
#查询电话号码还是地址?
Request=raw_input (' Phone number (p) or address (a)? ')
#使用正确的键:
Key=request
If request== ' P ': key= ' phone '
If request== ' a ': key= ' addr '
Person=people.get (name,{})
Label=labels.get (Key,key)
Result=person.get (Key, ' not available ')
print '%s '%s is%s. "% (Name,label,result)
>>> ================================ RESTART ================================
>>>
Name:gumby
Phone number (p) or address (a)? Batting average
Gumby ' s batting average is not available.
5, Has_key
The Has_key method can check if the dictionary contains the given key, and the expression D.has_key (k) is equivalent to the expression K in D
The code is as follows:
>>> d={}
>>> d.has_key (' name ')
False
>>> d[' name ']= ' Eric '
>>> d.has_key (' name ')
True
6. Items and Iteritems
The items method returns all dictionary items as a list, each of which comes from (the key, the value), but the items are returned with no special order
The code is as follows:
>>> d={' title ': ' Python Web Site ', ' url ': ' http://www.python.org ', ' spam ': 0}
>>> D.items ()
[(' url ', ' http://www.python.org '), (' spam ', 0), (' title ', ' Python Web Site ')]
The Iteritems method works roughly the same, but returns an iterator object instead of a list:
The code is as follows:
>>> It=d.iteritems ()
>>> it
>>> List (IT)
[(' url ', ' http://www.python.org '), (' spam ', 0), (' title ', ' Python Web Site ')]
7. Pop
The Pop method is used to get the value corresponding to the given key and then remove the key-value pair from the dictionary
The code is as follows:
>>> d={' x ': 1, ' Y ': 2}
>>> d.pop (' x ')
1
>>> D
{' Y ': 2}
8, Popitem
The Popitem method is similar to List.pop, which pops up the last element of the list. But popitem pops up random entries.
The code is as follows:
>>> d={' title ': ' Python Web Site ', ' url ': ' http://www.python.org ', ' spam ': 0}
>>> D
{' URL ': ' http://www.python.org ', ' spam ': 0, ' title ': ' Python Web Site '}
>>> D.popitem ()
(' url ', ' http://www.python.org ')
>>> D
{' spam ': 0, ' title ': ' Python Web Site '}
9, SetDefault
The SetDefault method is somewhat similar to the Get method, besides, SetDefault can also set the corresponding key value without the given key in the dictionary.
The code is as follows:
>>> d={}
>>> d.setdefault (' name ', ' N/A ')
' N/A '
>>> D
{' name ': ' N/A '}
>>> d[' name ']= ' Gumby '
>>> d.setdefault (' name ', ' N/A ')
' Gumby '
>>> D
{' name ': ' Gumby '}
10. Update
The Update method can update another dictionary with one dictionary entry:
The code is as follows:
>>> d={
' title ': ' Python Web Site ',
' URL ': ' http://www.python.org ',
' Changed ': ' Mar 22:09:15 MET 2008 '
}
>>> x={' title ': ' Python Langue Website '}
>>> d.update (x)
>>> D
{' URL ': ' http://www.python.org ', ' changed ': ' Mar 22:09:15 MET ', ' title ': ' Python Langue Website '}
11. Values and Itervalues
The values method returns the value in the dictionary as a list (an iterator that itervalues the return value), which, unlike the list of returned keys, can contain duplicate elements in the list of returned values:
The code is as follows:
>>> d={}
>>> d[1]=1
>>> d[2]=2
>>> d[3]=3
>>> d[4]=1
>>> d.values ()
[1, 2, 3, 1]