Explore the dictionary container in Python in detail

Source: Internet
Author: User
This article mainly introduces the dictionary container in Python. This article is from the technical documentation on the IBM official website. For more information, see Dictionary

We have all used language dictionaries to find the definitions of unknown words. The language dictionary provides a set of standard information for a given word (such as python. This system associates definitions and other information with actual words. Use words as the key positioner to find information of interest. This concept extends to the Python programming language and becomes a special container type called dictionary.

The dictionary data type exists in many languages. It is sometimes called an associated array (because the data is associated with a key value) or as a hash. But in Python, dictionary is a good object, so it is easy for new programmers to use it in their own programs. According to the official statement, dictionary in Python is a heterogeneous and variable ing container data type.
Create a dictionary

The previous articles in this series introduced some container data types in the Python programming language, including tuple, string, and list (see references ). The similarities between these containers are that they are all based on sequences. This means that you need to access the elements in these sets based on the position of the elements in the sequence. Therefore, given a sequence named a, you can use digital indexes (such as a [0]) or fragments (such as a []) to access elements. The dictionary container type in Python differs from the three container types in that it is an unordered set. Instead of using the index number, the key value is used to access the elements in the set. This means that constructing a dictionary container is more complex than tuple, string, or list, because keys and corresponding values must be provided at the same time, as shown in listing 1.
Listing 1. create a dictionary in Python, part 1

>>> 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
 
  >>> 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 be non-numeric>>> d{'one': 1}>>> 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 shown in this example, creating a dictionary in Python requires a combination of curly braces and key-value pairs separated by colons. If a key-value combination is not provided, an empty dictionary is created. Using a key-value combination, you can create a dictionary with an element, and so on, until you need any scale. Like any container type, you can use the built-in len method to identify the number of elements in the collection.

The preceding example also demonstrates another important issue about the dictionary container. The key is not limited to integers. it can be any data type that is not easy to change, including integer, float, tuple, or string. Because 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 a dict object. To learn more about how to use the dictionary in Python, you can use the built-in help interpreter to understand the dict class, as shown in listing 2.
List 2. get help on dictionary

>>> help(dict)on class dict in module __builtin__:   dict(object)| dict() -> new empty dictionary.| 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 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 of the dict class indicates that you can use the constructor to directly create a dictionary without curly braces. Since you must provide more data when creating a dictionary than other container data types, it is not surprising that these creation methods are complex. However, it is not difficult to use a dictionary in practice, as shown in listing 3.
Listing 3. create a dictionary in Python, part 1

>>> l = [0, 1,2 , 3, 4, 5, 6, 7, 8, 9] >>> d = dict(l)(most recent call last): File "
 
  ", line 1, in ?: can't convert dictionary  update sequence element #0 to a sequence  >>> 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 an expression
 

You can see that Keys and data values are required to create a dictionary. The first attempt to create a dictionary from the list failed because no matching key-data value pair exists. The second and third examples demonstrate how to correctly create a dictionary: in the first case, use a list, where each element is a tuple; in the second case, A list is also used, but each element is another list. In both cases, the inner container is used to obtain the key-to-data value ING.

Another way to directly create a dict container is to directly provide key-to-data value ING. This technique allows you to explicitly define keys and their corresponding values. This method is not very useful because you can use curly brackets to complete the same task. In addition, as shown in the previous example, when this method is used, numbers cannot be used for keys. Otherwise, an exception is thrown.
Access and modify a dictionary

After a dictionary is created, you need to access the data contained in the dictionary. The access method is similar to accessing data in any Python container data type, as shown in listing 4.
Listing 4. accessing the elements in 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 "
 
  ", line 1, in ?: 6>>> d[:-1](most recent call last): File "
  
   ", line 1, in ?: unhashable type
  
 

We can see that the process of getting data values from a dictionary is almost the same as that of getting data from any container type. Place the key value in brackets after the container name. Of course, dictionary can have non-numeric key values. if you have never used this data type before, it takes some time to adapt to this problem. Because the order in the dictionary is not important (the order of data in the dictionary is arbitrary), the fragment function that can be used for other container data types is not available for the dictionary. An exception is thrown when you try to access data using a clip or a key that never exists.

The dictionary container in Python is also a variable data type, which means you can modify it after creating it. As shown in listing 5, you can add a new key-to-data value ING, modify existing mappings, and delete mappings.
Listing 5. modifying a dictionary

>>> d = {0: 'zero', 1: 'one', 2: 'two', 3: 'three'}>>> d[0]'zero'>>> d[0] = 'Zero'>>> 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'>>> d{0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}

Listing 5 demonstrates several key points. First, it is easy to modify the data value: assign the new value to the appropriate key. Second, it is easy to add a new key to the data value ing: allocate the relevant data to the new key value. Python automatically performs all processing. You do not need to call special methods such as append. For a dictionary container, order is not important, so it should be easy to understand, because it is not added to the container rather than after the dictionary. Finally, the del operator and the key to be deleted from the container are used to delete the ING.

One of the situations in listing 5 seems a bit strange. the key values are displayed in numerical order, and this order is the same as the insert ing order. Don't misunderstand-this is not always the case. The ing order in Python dictionary is arbitrary, and may change for different Python installations. even running the same code with the same Python interpreter multiple times may change. If different types of keys and data values are used in a dictionary, you can easily 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['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 keys and data values of different data types in a dictionary. You can also add a new type by modifying the dictionary. Finally, the generated dictionary order does not match the inserted data order. In essence, the order of elements in a dictionary is controlled by the actual implementation of the Python dictionary data type. The new Python interpreter can easily change this order, so it must not depend on the specific order of elements in the dictionary.
Programming with dictionary

As the official Python data type, dictionary supports most operations supported by other simple 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 < d2>>> d1 == d2>>> id(d1)>>> id(d2)>>> d2 = d1.copy()>>> d1 == d2>>> id(d1)>>> id(d2)

The preceding example creates two dictionaries and uses them to test the <relational operator. Although two dictionaries are rarely compared in this way, you can do this if necessary.

In this example, the dictionary assigned to the variable d1 is assigned to another variable d2. Note that the built-in id () method returns the same identifier value for d1 and d2, which means this is not a copy operation. To copy a dictionary, you can use the copy () method. From the last few lines in this example, we can see that the copy is exactly the same as the original dictionary, but the variable containing this dictionary has different identifiers.

When using a dictionary in a Python program, you may want to check whether the dictionary contains a specific key or value. As shown in listing 8, these checks are easy to execute.
Listing 8. conditional test and dictionary

>>> d = {0: 'zero', 3: 'a tuple', 'two': [0, 1, 2], 'one': 1}>>> d.keys()[0, 3, 'two', 'one']>>> 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 member relationship of the middle key or data value in a dictionary statement. The dictionary container data type provides several built-in methods, including the keys () method and the values () method (not demonstrated here ). These methods return a list containing the keys or data values in the called dictionary.

Therefore, to determine whether a value is a key in a dictionary, 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 values () method. However, you can use a dictionary name as a shorthand. This makes sense, because you generally want to know whether a data value (not a key value) is in a dictionary.

In "Discover Python, Part 6", you can see how easy it is to use the for loop to traverse elements in the container. The same technology applies to Python dictionary, as shown in listing 9.
Listing 9. iteration 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 a dictionary: using the Python iterator returned from the iterkeys (), itervalues (), or iteritems () method. (By the way, you can directly call appropriate methods on a dictionary, such as d. iterkeys (), to check whether these methods return an iterator instead of the container data type .) The iterkeys () method allows you to traverse the keys of a dictionary, while the itervalues () method allows you to traverse the data values contained in a dictionary. On the other hand, the iteritems () method allows you to traverse the key-to-data value ing at the same time.

Dictionary: another powerful Python container

This article discusses Python dictionary data types. Dictionary is a heterogeneous and variable-prone container that relies on key-to-data value ing (rather than specific numerical order) to access elements in the container. Accessing, adding, and deleting the elements in a dictionary is simple, and it is easy to use in composite statements, such as if statements or for loops. You can store all different types of data in a dictionary, and access the data by name or other composite key values (such as tuple, therefore, Python dictionary enables developers to write simple and powerful programming statements.

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.