Referencing a data structure by name. This type of structure is called mapping. The dictionary is the only built-in mapping type in Python. The values in the dictionary are not in a special order, but are stored in a specific key. Keys can be numbers, strings, or even tuples.
In some cases, dictionaries are more appropriate than lists:
1. Characterize the game board state, each key is a tuple composed of coordinate values;
2. Save the file modification times, use the file name as the key;
3. Digital Telephone/Address Book
If there is a list of people listed below:
>>> names = [' Alice ', ' Beth ', ' Cecil ', ' Earl ']
>>> numbers = [' 3123 ', ' 3125 ', ' 5654 ', ' 9877 ']
>>> numbers[names.index (' Cecil ')]
' 5654 '
>>>
Read the reader's question: Why use strings instead of integers to represent phone numbers?
>>> 0142
98
>>>
This cannot be used because of the reason for the system.
4.2 Creating and using dictionaries
Phonebook = {' Alice ': ' 1234 ', ' Beth ': 4321}
A dictionary consists of pairs of multiple keys and their corresponding values. The name is the key number is the value.
The keys in the dictionary are unique, and the values are not unique
4.2.1 Dict function
You can use the Dict function to build a dictionary from other mappings or such sequences.
>>> 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 arguments
>>> d = dict (name= ' Gumby ', age=42)
>>> D
{' Age ':, ' name ': ' Gumby '}
>>>
This may be the most useful feature of the dict function, but it can also be mapped as an argument to the Dict function to establish a dictionary with the same item as the mapping (if not with any parameters, the Dict function returns a new empty dictionary, like List,tuple and str). If another mapping is also a dictionary , you can also use the dictionary method copy later in this chapter.
4.4.4 Basic Dictionary Operations
The basic behavior of a dictionary is similar to a sequence in many ways:
1.len (d) Returns the number of items in D
2.D[K] Returns the value associated to the key K
3.D[K]=V associates the value V to the key K
4.del D[k] Delete entry with key K
5.K in D check for D for items with key K
Although dictionaries and lists have many of the same features, there are some important differences.
Key types: The keys of a dictionary are not necessarily integer data (but may also be) or other immutable types, such as floating-point (real), string, or tuple.
Add automatically: Even if the key does not exist in the dictionary at first, it can be assigned a value so that the dictionary creates a new item. You cannot associate a value to an index outside the list range.
Membership: The expression K in D (d is a dictionary) finds the key, not the value. The expression V in L (L is a list) is used to look up a value, not an index.
Checking the membership of a key in a dictionary is more efficient than checking the membership in the list, the larger the size of the data structure, the more obvious the efficiency gap between the two.
The 1th---------key can be the most powerful place for any immutable type-----dictionary. The 2nd is also very important.
>>> x = {}
>>> x[42] = ' Foobar '
>>> x
{$: ' Foobar '}
>>>
First, the program attempts to associate the string ' Foobar ' to the 42nd position of an empty list--------This is obviously not possible because the location does not exist at all. To make it possible, I had to initialize x with [None] * 43 or otherwise, not just []. However, the next example works very well. I'm associating ' Foobar ' with the null dictionary key 42, no problem! The new item has been added to the dictionary.
4.1 Dictionary Examples
#!/usr/bin/env python
People = {
' Alice ': {' phone ': ' 2341 ', ' addr ': ' Foo drive 23 '},
' Beth ': {' phone ': ' 1234 ', ' addr ': ' Bar Street 32 '},
' Cecil ': {' phone ': ' 1234 ', ' addr ': ' Baz avendas 90 '}
}
Labels = {' Phone ': ' Phone number ', ' addr ': ' Address '}
Name = Raw_input (' Name: ')
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" is%s. "% \
(Name,labels[key],people[name][key])
Execution results
[Email protected] ~]#./python.py
Name:alice
Phone number (p) or address (a)? A
Alice's address is Foo Drive 23.
Formatted string for 4.2.3 Dictionary
>>> phonebook = {' Beth ': ' 9102 ', ' Alice ': ' 2341 ', ' Cecil ': ' 3258 '}
>>> Phonebook
{' Beth ': ' 9102 ', ' Alice ': ' 2341 ', ' Cecil ': ' 3258 '}
>>> "Cecil ' s phone number is% (Cecil) s."% phonebook
"Cecil ' s phone number is 3258."
>>>
In addition to the added string key, the conversion specifier works as before. When using a dictionary in this way, any number of conversion specifiers can be obtained as long as all the given keys can be found in the dictionary. This type of string formatting is useful in a template system
>>> template = "'
...
... <body>
...
... <p>% (text) s</p>
... <body> "
>>> data = {' title ': ' My home page ', ' text ': ' Welcome to My home page '}
>>> Print Template% data
<body>
<p>welcome to my home page</p>
<body>
>>>
4.2.4 Dictionary method
Like other built-in types, dictionaries have methods. These methods are useful, but may not be used as frequently as lists or string methods.
1.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
>>>
The first of these methods
>>> x = {}
>>> y = x
>>> x[' key ' = ' value '
>>> y
{' key ': ' Value '}
>>> x = {}
>>> y
{' key ': ' Value '}
>>>
The second Kind
>>> x = {}
>>> y = x
>>> x[' key ' = ' value '
>>> y
{' key ': ' Value '}
>>> X.clear ()
>>> y
{}
>>>
In both cases, X and y initially correspond to the same dictionary. In case 1, I emptied the x by associating it to a new empty dictionary, which has no effect on Y, and it is also associated with the original dictionary. This may be the desired behavior, but if you really want to empty all the elements in the original dictionary, you must use the Clear method.
2.copy
The Copy method returns a new dictionary with the same key-value pairs. This method implements a shallow copy because the value itself is the same, not the copy
>>> 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, the original dictionary is not affected when it is worth replacing in the copy, but if a value is modified (in-place, not replaced), the original dictionary also changes because the same value is stored in the original dictionary.
One way to avoid this problem is to use deep copy to copy all the values that it contains. You can use the Deepcopy function of the copy module to complete the operation:
>>> from copy import deepcopy
>>> d = {}
>>> d[' names ' = [' Alfred ', ' Bertrand ']
>>> C = d.copy ()
>>> DC = deepcopy (d)
>>> d[' names '].append (' Clive ')
>>> C
{' name ': [' Alfred ', ' Bertrand ']}
>>> DC
{' name ': [' Alfred ', ' Bertrand ']}
>>>
3.fromkeys
The Fromkeys method creates a new dictionary with the given key, and each key defaults to a value of none
>>> {}.fromkeys ([' Name ', ' age '])
{' Age ': none, ' Name ': none}
>>>
In the example, we first constructed an empty dictionary and then called its Fromkeys method, creating another dictionary---somewhat superfluous. You can also call a method directly above the type dict of all dictionaries.
>>> Dict.fromkeys ([' Name ', ' age '])
{' Age ': none, ' Name ': none}
>>>
If you do not want to use none as the default, you can also provide your own default value
>>> Dict.fromkeys ([' Name ', ' Age ', ' (unknown) ')
{' (unknown) ': None, ' age ': none, ' Name ': 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:
>>> d = {}
>>> print d[' name ']
Traceback (most recent):
File "<stdin>", line 1, in <module>
Keyerror: ' Name '
>>> print d.get (' name ')
None
>>>
You can see that when you use get to access a nonexistent key, there is no exception, and you get the None value. You can also customize the default values to replace None
>>> d.get (' name ', ' N/A ')
' N/A '
>>>
If a key exists, get is used just like a normal dictionary query:
>>> d[' name '] = ' Eric '
>>> d.get (' name ')
' Eric '
>>>
4-2 Dictionary Method examples
#!/usr/bin/env python
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)
5.has_key
The Has_key method can check whether the dictionary contains the given key. The expression D.has_key (k) is equivalent to the expression K in D. Which way to use depends largely on your personal preferences.
>>> d = {}
>>> d.has_key (' name ')
False
>>> d[' name '] = ' Eric '
>>> d.has_key (' name ')
True
>>>
6.items and Iteritems
The items method returns all dictionary entries in a list, each of which comes from the (key, value). But the items are returned with no special order.
>>> 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
>>> it = D.iteritems ()
>>> it
<dictionary-itemiterator Object at 0x7fc097934890>
>>> List (IT)
[(' url ', ' http://www.python.org '), (' spam ', 0), (' title ', ' Python web site ')]
7.keys and Iterkeys
The Keys method returns the keys in the dictionary as a list, while Iterkeys returns an iterator for the key
8.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.
>>> d = {' X ': 1, ' Y ': 2}
>>> d.pop (' x ')
1
>>> D
{' Y ': 2}
>>> d.pop (' y ')
2
>>> D
{}
>>>
9.popitem
The Popitem method is similar to List.pop, which pops up the last element of the list. But the difference is that popitem pops up random entries because the dictionary does not have "last element" or other concepts about the order. This method works very well if you want to remove and process items one after the other.
>>> d = {' URL ': 1, ' spam ': 2, ' title ': 3}
>>> D.popitem ()
(' URL ', 1)
>>> D
{' title ': 3, ' spam ': 2}
>>>
Although the Popitem and list pop methods are similar, there is no method in the dictionary that is equivalent to append. Because dictionaries are unordered, append-like methods are meaningless.
10.setdefault
The SetDefault method is somewhat similar to the Get method, which is the ability to get the value associated with a given key, and in addition, SetDefault can set the corresponding key value without the given key in the dictionary.
>>> d = {}
>>> d.setdefault (' name ', ' N/A ')
' N/A '
>>> D
{' name ': ' N/A '}
>>> d[' name '] = ' Gumby '
>>> d.setdefault (' name ', ' N/A ')
' Gumby '
>>> D
{' name ': ' Gumby '}
>>>
As you can see, when the key does not exist, SetDefault returns the default value and updates the dictionary accordingly. If the key exists, it returns its corresponding value, but does not change the dictionary. The default value is optional, and this is the same as get. If not set, none is used by default.
>>> d = {}
>>> print D.setdefault (' name ')
None
>>> D
{' name ': None}
>>>
11.update
The Update method can update another dictionary with one dictionary entry:
>>> d = {' title ': ' Python Web site ', ' uil ': ' http://www.baidu.com ', ' changed ': ' Mar 22:09:15 MET 2008 '}
>>> x = {' title ': ' Python language website '}
>>> d.update (x)
>>> D
{' changed ': ' Mar 22:09:15 MET ', ' uil ': ' http://www.baidu.com ', ' title ': ' Python language website '}
>>>
The items in the provided dictionary are added to the old dictionary and overwritten if the same key is available.
The Update method can be invoked in the same way as calling the Dict function, which is discussed earlier in this chapter, which means that update can be called with the map, the queue that owns (key, value) pairs, and the keyword parameters.
12.values and Itervalues
The values method returns the value in the dictionary as a list (an iterator that itervalues the return value). Unlike the list of returned keys, the returned list can contain duplicate elements:
>>> d = {}
>>> D[1] = 1
>>> D[2] = 2
>>> D[3] = 3
>>> D[4] = 1
>>> d.values ()
[1, 2, 3, 1]
>>>
This article is from the "linux_oracle" blog, make sure to keep this source http://pankuo.blog.51cto.com/8651697/1634653
A Dictionary of Python