Dictionary (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 a dictionary (dictionary).
The dictionary (dictionary) data type exists 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, the Dictionary (dictionary) is a good object, so even novice programmers can easily use it in their own programs. In a formal way, the Dictionary (dictionary) in Python is a heterogeneous, variable mapping container data type.
Create a 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 (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 a constructed dictionary (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 a 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<t Ype ' dict ' >>>> d = {} # Create an empty dictionary>>> len (d) >>> d = {1: ' One '} # Create A single item dictionary>>> d{1: ' One '}>>> len (d) >>> d = {' One ': 1} # The key value can is no N-numeric>>> 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 a dictionary in Python (dictionary) 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 (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 the Dictionary (dictionary). However, the values in the Dictionary (dictionary) can be of any data type.
Finally, this example illustrates that the underlying data type of the Dictionary (dictionary) in Python is the Dict object. To learn more about using the dictionary in Python (dictionary), you can use the built-in Help interpreter to understand the Dict class, as shown in Listing 2.
Listing 2. Get help with dictionaries (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] ...
With help on the Dict class, you can use constructors to create dictionaries directly (dictionary) without using curly braces. Since more data must be provided when creating dictionaries (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 a dictionary (dictionary) in practice, as shown in Listing 3.
Listing 3. Create a dictionary in Python (dictionary), part 2nd
>>> L = [0, 3, 4, 5, 6, 7, 8, 9] >>> d = dict (l) (most rece NT call last): File "<stdin>", line 1, in?: Can ' t convert dictionary Update sequence element #0 to a sequence ;>> L = [(0, ' zero '), (1, ' One '), (2, ' One '), (3, ' three ')]>>> d = dict (l) >>> d{0: ' Zero ', 1: ' One ', 2: ' Both ', 3: ' three '}>>> l = [[0, ' zero '], [1, ' one '], [2, ' one '], [3, ' three ']]>>> d{0: ' Zero ', 1: ' One ', 2: ' Both ', 3: ' three '}>>> d = dict (l) >>> d{0: ' Zero ', 1: ' One ', 2: ' Both ', 3: ' Three '}>>> D = Dict (zero=0, one=1, two=2, three=3) >>> d{' zero ': 0, ' three ': 3, ' one ': 2, ' one ': 1}>>> d = dict (0=ze Ro, 1=one, 2=two, 3=three): keyword can ' t be an expression
As you can see, creating a Dictionary (dictionary) requires key values and data values. The first attempt to create a dictionary from List (dictionary) failed because there is no matching key-data value pair. The second and third examples demonstrate how to correctly create a dictionary (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 dictionaries (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 "<stdin>", line 1, in?: 6&G T;>> D[:-1] (most recent): File ' <stdin> ', line 1, in?: Unhashable type
As you can see, the process of getting data values from a dictionary (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, The Dictionary (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 (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 dictionaries (dictionary). Attempting to use a fragment or attempting to access data from a nonexistent key throws an exception, indicating the related error.
The dictionary (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 (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 after the Dictionary (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 mappings in the Python Dictionary (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 (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 ]) <type ' str ' >>>> d[' one ']>>> type (d[' one ')) <type ' int ' >>>> d[' one '] = [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), ' one ': [0, 1, 2], ' One ': 1}>>> d[3] = ' A tuple ' >>> d{0: ' Zero ', 3: ' A tuple ', ' both ': [0, 1, 2], ' O Ne ': 1}
As this example shows, you can use keys and data values for different data types in a dictionary (dictionary). You can also add new types by modifying the dictionary (dictionary). Finally, the order of the resulting dictionary does not match the order in which the data is inserted. Essentially, the order of the Elements in the Dictionary (dictionary) is controlled by the actual implementation of the Python Dictionary (dictionary) data type. The new Python interpreter can easily change this order, so be sure not to rely on the elements in a particular order in the Dictionary (dictionary).
Programming with a dictionary (dictionary)
As a formal Python data type, the dictionary (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 dictionaries (dictionary) and uses them to test < relationship operators. Although you rarely compare two dictionaries in this way (dictionary), you can do so if you want.
The example then assigns the value assigned to the variable D1 Dictionary (dictionary) to 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 a dictionary (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 (dictionary), but the variable that holds the dictionary (dictionary) has a different identifier.
When you use a dictionary (dictionary) in a Python program, you probably want to check whether a dictionary (dictionary) contains a specific key or value. These checks are easy to implement, as shown in Listing 8.
Listing 8. Conditional Tests and dictionaries (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
The membership of a key or data value in a Test dictionary (dictionary) is simple. 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 (dictionary) that are called.
Therefore, to determine whether a value is a key in the Dictionary (dictionary), you should use the In operator to check whether the value is in the list of key values returned by 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 a dictionary (dictionary) masterpiece as shorthand notation. This is meaningful because you generally want to know whether a data value (rather than a key value) is in the Dictionary (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 the Python Dictionary (dictionary), as shown in Listing 9.
Listing 9. Iterations and dictionaries (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 demonstrates three ways to traverse a dictionary (dictionary): Use 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 method directly on the Dictionary (dictionary), such as D.iterkeys (). The Iterkeys () method allows traversing the keys of the Dictionary (dictionary), while the Itervalues () method allows traversal of the data values contained in the dictionary (dictionary). On the other hand, the Iteritems () method allows the mapping of key-to-data values to be traversed simultaneously.
Dictionary (Dictionary): Another powerful Python container
This article discusses the Python Dictionary (dictionary) data type. A dictionary (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 a dictionary (dictionary) is simple, and dictionaries (dictionary) are easy to use for compound statements, such as an if statement or a for loop. You can store all the different types of data in a dictionary (dictionary), which you can access by name or other composite key values (such as tuple), so the Python Dictionary (dictionary) enables developers to write concise and powerful programming statements.