Use of dictionaries
The fields in the real world and the fields in Python are built so that a particular word (key) can be easily traced to find its meaning (value).
In some cases, dictionaries are more appropriate than lists:
# characterize the game board state, each key is a tuple composed of coordinate values;
# Store the number of file changes, using the filename as the key;
# Digital Phone/Address Book
Create a list of people and four-bit extension numbers:
>>> names=[' Alice ', ' Beth ', ' Ceci ', ' Dee-dee ', ' Earl ']
>>> numbers=[' 2341 ', ' 9102 ', ' 3158 ', ' 0412 ', ' 5551 ']
>>> numbers[names.index (' Ceci ')] #通过此方法查询
' 3158 '
Creating and using dictionaries
Dictionaries can be created in the following ways:
phonebook={' Alice ': ' 2341 ', ' Beth ': ' 9102 ', ' Ceci ': ' 3158 '}
The dictionary consists of multiple keys and their corresponding values, in the above example, the name is the key and the phone number is the value.
dict function
You can use the Dict function to build a dictionary from a sequence of other mappings (such as other dictionaries) or (keys, values).
>>> itmes=[(' name ', ' Gumby '), (' Age ', 42)]
>>> d=dict (itmes)
>>> D
{' Age ':, ' name ': ' Gumby '}
>>> d[' name ']
' Gumby '
The Dict function can also create a dictionary from a keyword argument, as shown in the following example
>>> d=dict (name= ' Gumby ', age=42)
>>> D
{' Age ':, ' name ': ' Gumby '}
Basic Dictionary Operations
Phone Book Example
#简单数据库
#使用人名作为键的字典. Each person is represented by a dictionary whose key ' phone ' and ' addr ' represent their phone number and address respectively.
people={
' Alice ': {
' Phone ': ' 2341 ',
' Addr ': ' Foo drive 23 '
},
' Beth ': {
' Phone ': ' 9102 ',
' Addr ': ' Bar Street 42 '
},
' Cecil ': {
' Phone ': ' 3158 ',
' Addr ': ' Baz Avenue 90 '
}
}
#针对电话号码和地址使用的描述性标签, it will be used when the output is printed.
labels={
' Phone ': ' Phone number ',
' Addr ': ' Address '
}
Name=raw_input (' Name: ')
#查找电话号码还是地址? Use the correct key:
Request=raw_input (' Phone number (p) or address (a)? ')
#使用正确的键:
If request = = ' P ': key= ' phone '
If request = = ' A ': key= ' addr '
#如果名字是字典中的有效键才打印信息:
If name in People:print "%s '%s ' s%s."% (name, Labels[key], People[name][key])
--------------------------------------------
Name:beth
Phone number (p) or address (a)? p
Beth ' s phone number is 9102.
formatting strings for Dictionaries
>>> phonebook={' Beth ': ' 9102 ', ' Alice ': ' 2341 ', ' Cecil ': ' 3258 '}
>>> "Cecil ' s phone number is% (Cecil) s." %phonebook
"Cecil ' s phone number is 3258."
Dictionary method Clear
The clear method clears all items in the dictionary.
>>> d={}
>>> d[' name ']= ' Gumby '
>>> d[' age ']=42
>>> D
{' Age ':, ' name ': ' Gumby '}
>>> Returned_value=d.clear ()
>>> D
{}
>>> Print Returned_value
None
>>> x={}
>>> y=x
>>> x[' key ']= ' value '
>>> x
{' key ': ' Value '}
>>> x={}
>>> y
{' key ': ' Value '}
>>> x={}
>>> y=x
>>> x[' key ']= ' value '
>>> y
{' key ': ' Value '}
>>> X.clear ()
>>> y
{}
Copy
The Copy method returns an identical new dictionary with key-value pairs
>>> x={' username ': ' admin ', ' machines ': [' foo ', ' Bar ', ' Baz ']}
>>> y=x.copy ()
>>> y
{' username ': ' admin ', ' machines ': [' foo ', ' Bar ', ' Baz '}
>>> y[' username ']= ' MLH '
>>> y[' machines '].remove (' bar ')
>>> y
{' username ': ' MLH ', ' Machines ': [' foo ', ' Baz ']}
>>> x
{' username ': ' admin ', ' machines ': [' foo ', ' Baz '}}
You can see that the original dictionary is not affected when replacing a value in the replica dictionary, but the original dictionary is also affected when a value is modified
The way to avoid this problem is to use deep copy to copy all of the values that it contains, and you can use the Deepcopy function in the Copy module to complete
>>> from copy import deepcopy
>>> d={}
>>> d[' names ']=[' Alfred ', ' Bertrand ']
>>> c=d.copy ()
>>> C
{' names ': [' Alfred ', ' Bertrand ']}
>>> Dc=deepcopy (d)
>>> DC
{' names ': [' Alfred ', ' Bertrand ']}
>>> d[' names '].append (' Clive ')
>>> C
{' names ': [' Alfred ', ' Bertrand ', ' Clive ']}
>>> DC
{' names ': [' Alfred ', ' Bertrand ']}
Fromkeys
The Fromkeys method uses the given key to create a new dictionary, with each key corresponding to the default value of None
>>> {}.fromkeys ([' Name ', ' age '])
{' Age ': none, ' Name ': none}
>>> Dict.fromkeys ([' Name ', ' age '])
{' Age ': none, ' Name ': none}
>>> Dict.fromkeys ([' Name ', ' age '], ' (unknown) ')
{' Age ': ' (unknown) ', ' Name ': ' (unknown) '}
Get
Get is a more relaxed way to access a dictionary
>>> d={}
>>> print d[' name ']
Traceback (most recent):
File "<pyshell#5>", line 1, in <module>
Print d[' name ']
Keyerror: ' Name '
>>> print d.get (' name ')
None
>>> d.get (' name ', ' N/A ')
' N/A '
>>> d[' name ']= ' Eric '
>>> d.get (' name ')
' Eric '
Dictionary method examples
Simple database of #使用get ()
people={
' Alice ': {
' Phone ': ' 2341 ',
' Addr ': ' Foo drive 23 '
},
' Beth ': {
' Phone ': ' 9102 ',
' Addr ': ' Bar Street 42 '
},
' Cecil ': {
' Phone ': ' 3158 ',
' Addr ': ' Baz Avenue 90 '
}
}
#这里添加代码清单插入数据库的代码
labels={
' Phone ': ' Phone number ',
' Addr ': ' Address '
}
Name=raw_input (' Name: ')
#查找电话号码还是地址?
Request=raw_input (' Phone number (p) or address (a)? ')
#使用正确的键
Key=request #如果请求的既不是 ' P ' is also not ' a '
If request = = ' P ': key= ' phone '
If request = = ' A ': key= ' addr '
Default value provided by the #使用get ()
Person=people.get (name,{})
Label=labels.get (Key,key)
Result=person.get (Key, ' not available ')
print '%s '%s is%s. "% ( Name,label,result)
----------------------------------------
Name:beth
Phone number (p) or address (a)? Batting average
Beth's batting average is not available.
Has_key
The Has_key method can check if the dictionary has a given key
>>> d={}
>>> d.has_key (' name ')
False
>>> d[' name ']= ' Eric '
>>> d.has_key (' name ')
True
Items and Iteritems
The items method returns all dictionary entries in a list, each of which comes from (a key, a value). However, the item does not have a special order when it returns a value
>>> 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 acts roughly the same, but returns an iterator object instead of a list
>>> It=d.iteritems ()
>>> it
<dictionary-itemiterator Object at 0x02a87a80>
>>> list (IT) #将迭代器转换为列表
[(' url ', ' http://www.python.org '), (' spam ', 0), (' title ', ' Python web site ')]
Keys and Iterkeys
The Keys method returns a list of keys in a list, Iterkeys returns an iterator for the key
d={' title ': ' Python Web site ', ' url ': ' http://www.python.org ', ' spam ': 0}
>>> D.keys ()
[' url ', ' spam ', ' title ']
>>> Hs=d.iterkeys ()
>>> HS
<dictionary-keyiterator Object at 0x02a87a50>
>>> List (HS)
[' url ', ' spam ', ' title ']
Pop
The Pop method is used to obtain a value corresponding to the given key and then remove the key value from the dictionary.
>>> d={' x ': 1, ' Y ': 2}
>>> d.pop (' x ')
1
>>> D
{' Y ': 2}
Popitem
The Popitem method is similar to List.pop, which pops up the last element of the list, and Popitem pops up random items because the dictionary has no sequential concept
>>> d={' title ': ' Python Web site ', ' url ': ' http://www.python.org ', ' spam ': 0}
>>> D.popitem ()
(' url ', ' http://www.python.org ')
>>> D
{' spam ': 0, ' title ': ' Python Web site '}
SetDefault
The SetDefault method is somewhat similar to the Get method, which is the ability to obtain the relevant value of a given key, and in addition, SetDefault can set the key value without the given key.
>>> d={}
>>> d.setdefault (' name ', ' N/A ')
' N/A '
>>> D
{' name ': ' N/A '}
>>> d[' name ']= ' Gumby '
>>> d.setdefault (' name ', ' N/A ')
' Gumby '
>>> D
{' name ': ' Gumby '}
>>> d={}
>>> print D.setdefault (' name ')
None
>>> D
{' name ': None}
Update
The Update method can update another dictionary with one dictionary
>>> d={' title ': ' Python Web site ', ' url ': ' http://wwww.python.org ', ' changed ': ' Mar 22:09:15 met 2008 '}
>>> x={' title ': ' Python language website '}
>>> d.update (x)
>>> D
{' URL ': ' http://wwww.python.org ', ' changed ': ' Mar 22:09:15 met ', ' title ': ' Python language website '}
Values and Itervalues
The values method returns the value in the dictionary as a list, Itervalues returns an iterator
>>> d={}
>>> d[1]=1
>>> d[2]=2
>>> d[3]=3
>>> d[4]=1
>>> d.values ()
[1, 2, 3, 1]
>>> it=d.itervalues ()
>>> it
<dictionary-valueiterator Object at 0x028466f0>
>>> List (IT)
[1, 2, 3, 1]
Python Learning Notes (dictionary)