Dictionary
We've all used a language dictionary to find the definition of a word we don't know. A language dictionary provides a standard set of information for a given word, such as Python. This system associates the definition and other information with the actual word (map). Use words as key locators to find information of interest. This concept extends to the Python programming language and becomes a special container type called dictionary.
Dictionary data types exist in many languages. It is sometimes called an associative array (because the data is associated with a key value), or as a hash table. But in Python, dictionary is a good object, so even novice programmers can easily use it in their own programs. In a formal way, dictionary in Python is a heterogeneous, variable mapping container data type.
Create dictionary
The previous articles in this series describe some of the container data types in the Python programming language, including tuple, string, and list (see Resources). The similarity of these containers is that they are all sequence-based. This means that the elements in these collections are accessed based on the position of the elements in the sequence. So, given a sequence named a, you can use a numeric index (such as a[0]) or a fragment (such as A[1:5]) to access the element. The dictionary container type in Python differs from these three container types in that it is an unordered collection. Instead of following the index number, the key value is used to access the elements in the collection. This means that constructing a dictionary container is more complex than a tuple, string, or list, because both the key and the corresponding value must be supplied, as shown in Listing 1.
Listing 1. Create dictionary in Python, part 1th
>>> D = {0: ' zero ', 1: ' One ', 2: ' One ', 3: ' Three ', 4: ' Four ', 5: ' Five '}>>> d{0: ' Zero ', 1: ' One ', 2 : ' Both ', 3: ' Three ', 4: ' Four ', 5: ' Five '}>>> len (d) >>> type (d) # Base object is the Dict class
>>> d = {} # Create an empty dictionary>>> len (d) >>> d = {1: ' One '} # Create a Si Ngle Item dictionary>>> d{1: ' One '}>>> len (d) >>> d = {' One ': 1} # The key value can be non-num Eric>>> d{' one ': 1}>>> d = {' One ': [0, 3, 4, 5, 6, 7, 8, 9]}>>> d{' one ': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}
As this example shows, creating dictionary in Python uses curly braces and key-value combinations separated by colons. If a key-value combination is not provided, an empty dictionary is created. With a key-value combination, you create a dictionary with one element, and so on, until you need any size. As with any container type, you can use the built-in Len method to pinpoint the number of elements in the collection.
The previous example also demonstrates another important issue with the dictionary container. The key is not limited to integers; it can be any immutable data type, including integer, float, tuple, or string. Because the list is variable, it cannot be used as a key in dictionary. However, the value in dictionary can be of any data type.
Finally, this example shows that the underlying data type of dictionary in Python is the Dict object. To learn more about using dictionary in Python, you can use the built-in Help interpreter to understand the Dict class, as shown in Listing 2.
Listing 2. Get help with Dictionary
>>> Help (Dict) on class dict in module __builtin__: dict (object) | dict (), New empty dictionary.| dict (map ping), new dictionary initialized from a mapping object ' s| (key, value) pairs.| Dict (seq), new dictionary initialized as if via:| d = {}| For K, V in seq:| d[k] = v| dict (**kwargs)-New dictionary initialized with the Name=value pairs| In the keyword argument list. For Example:dict (one=1, two=2) | | Methods Defined here:| | __cmp__ (...) | x.__cmp__ (y) <==> cmp (x, y) | | __contains__ (...) | X.__contains__ (y) <==> y in x| | __delitem__ (...) | x.__delitem__ (y) <==> del x[y] ...
The Help for the Dict class indicates that you can use constructors to create dictionary directly without using curly braces. Since you must provide more data when creating dictionary than other container data types, it is not surprising that these methods are more complex to create. However, it is not difficult to use dictionary in practice, as shown in Listing 3.
Listing 3. Create dictionary in Python, part 2nd
>>> L = [0, 3, 4, 5, 6, 7, 8, 9] >>> d = dict (l) (most recent call last): File "
", Li NE 1, in?: Can ' t convert dictionary Update sequence element #0 to a sequence >>> l = [(0, ' zero '), (1, ' One '), (2, ' both '), (3, ' three ')]>>> d = dict (l) >>> d{0: ' Zero ', 1: ' One ', 2: ' One ', 3: ' Three '}>>& Gt l = [[0, ' zero '], [1, ' one '], [2, ' one '], [3, ' three ']]>>> d{0: ' Zero ', 1: ' One ', 2: ' One ', 3: ' Three '}>>&G T D = dict (l) >>> d{0: ' Zero ', 1: ' One ', 2: ' One ', 3: ' three '}>>> d = dict (zero=0, one=1, two=2, three=3) & gt;>> d{' zero ': 0, ' three ': 3, ' one ': 2, ' one ': 1}>>> d = dict (0=zero, 1=one, 2=two, 3=three): keyword can ' T is an expression
As you can see, creating dictionary requires key values and data values. The first attempt to create a dictionary from the list failed because there is no matching key-data value pair. The second and third examples demonstrate how to correctly create dictionary: In the first case, use a list, where each element is a tuple, and in the second case a list is used, but each of these elements is another list. In both cases, the inner container is used to obtain a mapping of key-to-data values.
Another way to directly create a dict container is to directly provide a mapping of key-to-data values. This technique allows you to explicitly define a key and its corresponding value. This method is not very useful because you can use curly braces to accomplish the same task. Also, as shown in the previous example, a number cannot be used for a key in this way, or an exception will be thrown.
Accessing and modifying Dictionary
Once you have created dictionary, you need access to the data contained therein. Access is similar to accessing data from any Python container data type, as shown in Listing 4.
Listing 4. Accessing elements in the dictionary
>>> d = dict (zero=0, one=1, two=2, three=3) >>> d{' zero ': 0, ' three ': 3, ' one ': 2, ' one ': 1}>>> d[' zero ']>>> d[' three ']>>> d = {0: ' zero ', 1: ' One ', 2: ' One ', 3: ' Three ', 4: ' Four ', 5: ' Five '}>& Gt;> d[0] ' zero ' >>> d[4] ' four ' >>> d[6] (most recent call last): File "
", line 1, in?: 6& Gt;>> D[:-1] (most recent): File "
", line 1, in?: unhashable type
As you can see, the process of getting data values from dictionary is almost identical to getting data from any container type. Place the key value in the square brackets behind the container name. Of course, dictionary can have non-numeric key values, and if you have not used this data type before, it will take some time to adapt. Because the order in the dictionary is unimportant (the order of the data in the dictionary is arbitrary), the fragment functionality that can be used for other container data types is not available for dictionary. Attempting to use a fragment or attempting to access data from a nonexistent key throws an exception, indicating the related error.
The dictionary container in Python is also a variable data type, which means that you can modify it after you create it. As shown in Listing 5, you can add a new key-to-data-value mapping, modify the existing mappings, and delete the mappings.
Listing 5. Modify Dictionary
>>> D = {0: ' zero ', 1: ' One ', 2: ' One ', 3: ' Three '}>>> d[0] ' zero ' >>> d[0] = ' zero ' >>> d{0: ' Zero ', 1: ' One ', 2: ' Both ', 3: ' Three '}>>> d[4] = ' four ' >>> d[5] = ' five ' >>> d{0: ' Zero ', 1: ' One ', 2: ' One ', 3: ' Three ', 4: ' Four ', 5: ' Five '}>>> del d[0]>>> d{1: ' One ', 2: ' One ', 3: ' Three ', 4 : ' Four ', 5: ' Five '}>>> d[0] = ' zero ' >>> d{0: ' Zero ', 1: ' One ', 2: ' A ', ' 3: ' Three ', 4: ' Four ', 5: ' FIV E '}
Listing 5 shows a few highlights. First, it is very simple to modify the data value: Assign the new value to the appropriate key. Second, it is also simple to add a new key-to-data value mapping: Assign the relevant data to the new key value. Python does all the processing automatically. There is no need to call special methods such as append. For dictionary containers, the order is unimportant, so this should be understood, because instead of attaching the map behind dictionary, it is added to the container. Finally, the way to delete a map is to use the DEL operator and the key that should be removed from the container.
In Listing 5, there is a situation that looks a bit strange, and the key values are displayed in numerical order, and the order is the same as the order in which the mappings are inserted. Don't misunderstand-it's not always the case. The order of the Mappings in Python dictionary is arbitrary, and may vary for different python installations, and even running the same code multiple times with the same Python interpreter will change. If you use different types of keys and data values in a dictionary, it is easy to see this, as shown in Listing 6.
Listing 6. heterogeneous containers
>>> D = {0: ' zero ', ' One ': 1} >>> d{0: ' zero ', ' one ': 1}>>> d[0] ' zero ' >>> type (d[0 ])
>>> d[' one ']>>> type (d[' one ')
>>> d[' "" = [0, 1, 2] > >> d{0: ' Zero ', ' both ': [0, 1, 2], ' One ': 1}>>> d[3] = (0, 1, 2, 3) >>> d{0: ' Zero ', 3: (0, 1, 2, 3) , ' both ': [0, 1, 2], ' One ': 1}>>> d[3] = ' A tuple ' >>> d{0: ' Zero ', 3: ' A tuple ', ' one ': [0, 1, 2], ' one ': 1}
As this example shows, you can use keys and data values for different data types in a dictionary. You can also add a new type by modifying dictionary. Finally, the order of the resulting dictionary does not match the order in which the data is inserted. Essentially, the order of elements in dictionary is controlled by the actual implementation of the Python dictionary data type. The new Python interpreter can easily change this order, so be sure not to rely on the element's specific order in dictionary.
Programming with the Dictionary
As a formal Python data type, dictionary supports most operations supported by other simpler data types. These operations include general relational operators such as <, >, and = =, as shown in Listing 7.
Listing 7. General relational operators
>>> D1 = {0: ' zero '}>>> d2 = {' zero ':0}>>> d1 < d2>>> d2 = d1>>> D1 < D 2>>> D1 = = d2>>> ID (d1) >>> ID (d2) >>> D2 = d1.copy () >>> D1 = d2>>> I D (D1) >>> ID (D2)
The previous example creates two dictionary and uses them to test the < relationship operator. Although it is rare to compare two dictionary in this way, you can do so if necessary.
The example then assigns the value assigned to the variable D1 to the dictionary of the other variable D2. Note that the built-in ID () method returns the same identifier value for D1 and D2, which means that this is not a copy operation. To copy dictionary, you can use the copy () method. As you can see from the last lines of this example, the copy is exactly the same as the original dictionary, but the variable that holds the dictionary has a different identifier.
When using dictionary in a Python program, you will most likely want to check whether a specific key or value is included in the dictionary. These checks are easy to implement, as shown in Listing 8.
Listing 8. Conditional Testing and Dictionary
>>> D = {0: ' zero ', 3: ' A tuple ', ' both ': [0, 1, 2], ' One ': 1}>>> d.keys () [0, 3, ' one ', ' one ']>>> ; If 0 in D.keys (): ... print ' True ' ... >>> if ' one ' in D: ... print ' True ' ... >>> if ' four ' in D: ... print ' Dictionary contains four ' ... elif ' in D: ... print ' Dictionary contains ' ... contains
It is very simple to test the membership of a key or data value in a dictionary. The dictionary container data type provides several built-in methods, including the keys () method and the Values () method (not shown here). These methods return a list that contains the keys or data values in the dictionary that were called.
Therefore, to determine whether a value is a key in dictionary, you should use the In operator to check whether the value is in the list of key values returned by calling the keys () method. You can use similar operations to check whether a value is in the list of data values returned by the call to the values () method. However, you can use dictionary masterpieces as shorthand notation. This is meaningful because you generally want to know if a data value (not a key value) is in dictionary.
In Discover Python, Part 6, you see how easy it is to traverse the elements in a container using a for loop. The same technique applies to Python dictionary, as shown in Listing 9.
Listing 9. Iterations and Dictionary
>>> D = {0: ' zero ', 3: ' A tuple ', ' both ': [0, 1, 2], ' One ': 1}>>> for K in D.iterkeys (): ... Print D[k] ... tuple[0, 1, 2]>>> for V in D.itervalues (): ... Print V ... tuple[0, 1, 2]>>> for K, V in D.iteritems (): ... print ' d[', K, '] = ', v ... [0] = zero[3] = a tuple[-b] = [0, 1, 2][one] = 1
This example shows three ways to traverse dictionary: Using the Python iterator returned from the Iterkeys (), itervalues (), or Iteritems () methods. (By the way, you can check whether these methods return an iterator instead of a container data type by calling the appropriate methods directly on the dictionary, such as D.iterkeys (). The Iterkeys () method allows traversal of dictionary keys, while the Itervalues () method allows traversal of the data values contained in the dictionary. On the other hand, the Iteritems () method allows the mapping of key-to-data values to be traversed simultaneously.
Dictionary: Another powerful Python container
This article discusses the Python dictionary data type. Dictionary is a heterogeneous, variable container that relies on the mapping of key-to-data values (rather than a particular number order) to access the elements in the container. accessing, adding, and deleting elements in dictionary is simple, and dictionary is easy to use for compound statements, such as an if statement or a for loop. You can store all of the different types of data in dictionary, which can be accessed by name or by other composite key values, such as tuple, so Python dictionary enables developers to write concise and powerful programming statements.