Explore the dictionary container _python in Python in detail

Source: Internet
Author: User
Tags stdin

Dictionary

We have all used language dictionaries to find definitions of words that 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 into 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. Officially, 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 similarities between these containers are that they are all based on sequences. This means that you want to access the elements in these collections based on the position of the elements in the sequence. So, given a sequence named a, you can access the element by using a numeric index (such as a[0]) or a fragment (such as a a[1:5]). The dictionary container type in Python differs from these three container types in that it is a unordered collection. Instead of the index number, the key value is used to access the elements in the collection. This means that constructing a dictionary container is more complicated than tuple, string, or list because 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: ' Two ', 3: ' Three ', 4: ' Four ', 5: ' Five '}
>>> D
{0: ' zero ', 1  : ' One ', 2: ' Two ', 3: ' Three ', 4: ' Four ', 5: ' Five '}
>>> len (d)
>>> type (d)     # Base object is The Dict class
<type ' Dict ' >
>>> d = {}      # Create an empty dictionary
>>> len (d) 
   >>> d = {1: ' One '} # Create a single item dictionary
>>> d
{1: ' One '}
>>> L En (d)
>>> d = {' One ': 1} # The key value can be non-numeric
>>> d
{' One ': 1}
>&G T;> d = {' One ': [0, 1,2, 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 a colon-delimited key-value combination. If no key-value combination is 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 find out the number of elements in the collection.

The previous example also demonstrates another important issue with respect to the dictionary container. The key is not limited to integers; it can be any variable 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 >| Dict (mapping)-> 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 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]
...

For help with the Dict class, you can use constructors to create dictionary directly, instead of curly braces. Since it is necessary to provide more data when creating dictionary than other container data types, it is not surprising that these creation methods are more complex. 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, 1,2, 3, 4, 5, 6, 7, 8, 9] >>> d = dict (l) (most recent call Last): File "<stdin>", Line 1, in: Can ' t convert dictionary Update sequence element #0 to a sequence >&G t;> L = [(0, ' zero '), (1, ' One '), (2, ' two '), (3, ' three ')] >>> d = dict (l) >>> d {0: ' zero ', 1: ' One ', 2: ' Two ', 3: ' Three '} >>> l = [[0, ' zero '], [1, ' one '], [2, ' two '], [3, ' three ']] >>> d {0: ' zero ', 1 : ' One ', 2: ' Two ', 3: ' Three '} >>> d = Dict (l) >>> d {0: ' zero ', 1: ' One ', 2: ' Two ', 3: ' Three '} >>  ;> d = dict (zero=0, one=1, two=2, three=3) >>> d {' zero ': 0, ' three ': 3, ' two ': 2, ' One ': 1} >>> D = Dict (0=zero, 1=one, 2=two, 3=three): keyword can ' t be a 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 show how to create dictionary correctly: in the first case, use a list where each element is a tuple, and in the second case a list is used, but each element is another list. In both cases, the inner container is used to obtain the mapping of the key to the data value.

Another way to create a dict container directly is to provide a mapping of the key to the data value directly. 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. In addition, as shown in the previous example, a number cannot be used for keys in this way, or it can cause an exception to be thrown.
Accessing and modifying dictionary

After you create a dictionary, you need to access the data it contains. The access pattern is similar to accessing data in 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, ' two ': 2, ' one ': 1}
   >>> d[' zero ']
>>> d[' three ']
>>> d = {0: ' zero ', 1: ' One ', 2: ' Two ', 3: ' Three ', 4 : ' Four ', 5: ' Five '}
>>> d[0]
' zero '
>>> d[4]
' four '
>>> D[6] (most Recent call last):
 file "<stdin>", line 1, in?: 6
>>> D[:-1] (most recent called last):
 file " <stdin> ", line 1, in?: Unhashable type

As you can see, the process of getting data values from dictionary is almost exactly the same as fetching data from any container type. Place the key value in the square brackets that follow the container name. Of course, dictionary can have non-numeric key values, and if you haven't used this data type before, it will take some time to adapt. Because order is unimportant in dictionary (the Order of the data in Dictionary is arbitrary), the fragment functionality that can be used for other container data types is not available for dictionary. Attempting to use fragments or attempting to access data from a nonexistent key throws an exception, indicating the associated error.

The dictionary container in Python is also a variable data type, which means that it can be modified after it is created. As shown in Listing 5, you can add a new key to the data value mapping, you can modify the existing mappings, and you can delete the mappings.
Listing 5. Modify Dictionary

>>> D = {0: ' zero ', 1: ' One ', 2: ' Two ', 3: ' Three '}
>>> d[0]
' zero '
>>> d[0 ' = ' Zer  O '
>>> d
{0: ' Zero ', 1: ' One ', 2: ' Two ', 3: ' Three '}
>>> d[4] = ' Four '
>>> d[5] = ' Five '
>>> D
{0: ' Zero ', 1: ' One ', 2: ' Two ', 3: ' Three ', 4: ' Four ', 5: ' Five '}
>>> del d [0]
>>> d
{1: ' One ', 2: ' Two ', 3: ' Three ', 4: ' Four ', 5: ' Five '}
>>> d[0] = ' zero '
>>&G T D
{0: ' zero ', 1: ' One ', 2: ' Two ', 3: ' Three ', 4: ' Four ', 5: ' Five '}

Listing 5 illustrates a few points. First, it is simple to modify the data value: Assign the new value to the appropriate key. Second, adding a new key to the data value mapping is also simple: assigning related data to a new key value. Python automatically does all the processing. You do not need to invoke special methods such as append. In the case of the dictionary container, the order is not important, so this should be understood because it is not appended to the dictionary, it is added to the container. Finally, the way to delete a mapping is to use the DEL operator and the key that should be removed from the container.

One of the things that looks strange in Listing 5 is that 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--this is not always the case. The sequence of mappings in the Python dictionary is arbitrary, and may change for different Python installations, or even run the same code multiple times with the same Python interpreter. This is easy to see if you use different types of keys and data values in a dictionary, 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[' two '] = [0, 1, 2] 
>>> d
{0: ' zero ', ' two ': [0, 1, 2], ' one ': 1}
   >>> d[3] = (0, 1, 2, 3)
>>> D
{0: ' zero ', 3: (0, 1, 2, 3), ' two ': [0, 1, 2], ' One ': 1}
>>> d[3] = ' A tuple '
>>> D
{0: ' zero ', 3: ' A tuple ', ' two ': [0, 1, 2], ' One ': 1}

As shown in this example, you can use key and data values of 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. In essence, 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 particular order of elements in the dictionary.
Programming with 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
&G t;>> D1 < d2
>>> D1 = = D2
>>> ID (d1)
>>> ID (D2)
>>> d2 = D1. Copy ()
>>> D1 = = D2
>>> ID (d1)
>>> ID (D2)

The preceding example creates two dictionary and uses them to test the < relationship operator. Although it is rare to compare two dictionary in this way, this can be done if necessary.

The example then assigns the value assigned to the variable D1 to another variable D2. Note that the built-in ID () method returns the same identifier value for D1 and D2, which indicates that this is not a copy operation. To copy dictionary, you can use the copy () method. As you can see from the last few lines in this example, the copy is exactly the same as the original dictionary, but the variable that holds the dictionary has a different identifier.

When you use dictionary in a Python program, you will most likely want to check whether the dictionary contains a specific key or value. As shown in Listing 8, these checks are easy to implement.
Listing 8. Conditional Testing and Dictionary

>>> D = {0: ' zero ', 3: ' A tuple ', ' two ': [0, 1, 2], ' One ': 1}
>>> D.keys ()
[0, 3, ' two ', ' one ']< c3/>>>> if 0 in D.keys ():
.   . print ' True '
... 
>>> if ' one ' in D:
...   print ' True '
... 
>>> if ' four ' in D:
...   print ' Dictionary contains four '
... elif ' two ' in D:
...   print ' Dictionary contains two '
... contains two

It is easy 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 are being invoked, respectively.

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 the call keys () method. You can use similar actions to check whether a value is in the list of data values returned by calling the values () method. However, you can use the dictionary masterpiece as the shorthand notation. This is meaningful because it is generally desirable to know whether a data value (rather than a key value) is in dictionary.

In Discover Python, Part 6, you see how easy it is to use a for loop to traverse the elements in a container. The same technique applies to Python dictionary, as shown in Listing 9.
Listing 9. Iterations and Dictionary

>>> D = {0: ' zero ', 3: ' A tuple ', ' two ': [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[two] = [0, 1, 2][one] = 1


   

This example demonstrates three ways to traverse dictionary: Use the Python iterator returned from the Iterkeys (), itervalues (), or Iteritems () method. (By the way, you can check whether these methods return an iterator rather than a container data type by calling the appropriate method directly on the dictionary, such as D.iterkeys (). The Iterkeys () method allows traversal of the dictionary key, while the Itervalues () method allows traversal of the dictionary contained data values. On the other hand, the Iteritems () method allows simultaneous traversal of a key to a data value mapping.

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 specific number order) to access the elements in the container. accessing, adding, and deleting elements in dictionary are simple, and dictionary can be easily used for compound statements, such as if statements or for loops. You can store all the different types of data in dictionary, and you can access the data by name or other composite key values (such as tuple), so Python dictionary enables developers to write concise and powerful programming statements.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.