Explore the dictionary container in Python in detail

  • 2020-05-09 18:49:29
  • OfStack

dictionary

We've all used language dictionaries to look up definitions of words we don't know. A language dictionary provides a standard set of information for a given word, such as python. This system associates definitions and other information with the actual words. Use the word as a key locator 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 referred to as an associative array (because the data is associated with a key value) or as a hash table. But in Python, dictionary is a nice object, so it's easy for even novice programmers to use it in their own programs. Formally, dictionary in Python is a heterogeneous, mutable mapping container data type.
Create dictionary

The previous articles in this series covered some container data types in the Python programming language, including tuple, string, and list (see resources). The similarity between these containers is that they are sequence-based. This means accessing elements in these collections based on their position in the sequence. So, given a sequence named a, you can access elements using either a numeric index (such as a[0]) or a fragment (such as a[1:5]). The dictionary container type in Python differs from these three container types in that it is an unordered collection. Instead of using an index number, you use key values to access elements in the collection. This means that constructing an dictionary container is a little more complex than building an tuple, string, or list container, because you must provide both the key and the corresponding value, as shown in listing 1.
Listing 1. Creating 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
<type '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 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, dictionary is created in Python using curly braces and colon-separated key-value combinations. If no key-value combination is provided, an empty dictionary is created. Using one key-value combination, you create an dictionary with one element, and so on, up to whatever size you need. As with any container type 1, you can use the built-in len method to find out the number of elements in the collection.

The previous example also demonstrated another important issue with the dictionary container. Keys are not limited to integers; It can be any immutable data type, including integer, float, tuple, or string. Because list is mutable, it cannot be used as a key in dictionary. But the values in dictionary can be of any data type.

Finally, this example shows that the underlying data type for dictionary in Python is an dict object. To take a step forward and learn how to use dictionary in Python, you can use the built-in help interpreter to learn about 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(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]
...

Help with the dict class points out that you can create dictionary directly using a constructor, without using curly braces. Since you must provide more data when creating dictionary than other container data types, it is not surprising that these creation methods are complex. However, it is not difficult to use dictionary in practice, as shown in listing 3.
Listing 3. Create dictionary in Python, part 2


>>> 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
  
>>> 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

As you can see, creating dictionary requires both key and data values. The first attempt to create dictionary from list failed because there was no matching key-data value pair. The second and third examples demonstrate how to create dictionary correctly: in case 1, use 1 list, where each element is 1 tuple; In the second case, one list is also used, but each element is another list. In both cases, the inner container is used to obtain key-to-data value mappings.

Another way to create an dict container directly is to provide a key-to-data value mapping directly. This technique allows you to explicitly define keys and their corresponding values. This method is not very useful, because you can use curly braces to do the same thing. In addition, as shown in the previous example, you cannot use Numbers for keys in this manner, which would cause an exception to be thrown.
Access and modify dictionary

Once dictionary is created, you need to access the data it contains. Access 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 "<stdin>", line 1, in ?: 6
>>> d[:-1](most recent call 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 getting data from any container type. Place the key value in the square brackets following 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 get used to this point. Because order is not important in dictionary (the order of data in dictionary is arbitrary), the fragment functionality that can be used for other container data types is not available for dictionary. An attempt to access the data using a fragment or an attempt to access the data with a key that never existed throws an exception, indicating a related error.

The dictionary container in Python is also a mutable data type, which means you can modify it after you create it. As shown in listing 5, you can add a new key-to-data value mapping, modify an existing mapping, or remove the mapping.
Listing 5. Modify 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 illustrates several key points. First, modifying the data value is simple: assign the new value to the appropriate key. Second, the mapping of adding new keys to data values is simple: assign related data to the new key values. Python does all the processing automatically. There is no need to call special methods like append. For the dictionary container, order is not important, so this should make sense, because instead of attaching a mapping to dictionary, you add it to the container. Finally, the mapping is removed by using the del operator and the key that should be removed from the container.

One situation in listing 5 that seems odd is that the key values are displayed in numeric order, and in the same order as the insert map. Don't get me wrong -- this isn't always the case. The order of the mapping in Python dictionary is arbitrary, and may vary for different Python installations, or even for multiple runs of the same code using the same 1 Python interpreter. If you use different types of keys and data values in one dictionary, you can easily see this point, as shown in listing 6.
Listing 6. Heterogeneous container


>>> 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 this example shows, you can use keys and data values of different data types in 1 dictionary. You can also add new types by modifying dictionary. Finally, the order of dictionary generated does not match the order of the inserted data. Essentially, the order of the elements in dictionary is controlled by the actual implementation of the Python dictionary data type. The new Python interpreter can easily change this 1 order, so the 1 must not depend on the specific order of elements in dictionary.
Programming with dictionary

As a formal Python data type, dictionary supports most of the operations supported by other, simpler data types. These operations include 1-like relational operators, such as < , > And ==, as shown in listing 7.
Listing 7.1 general relationship operator


>>> 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 previous example created two dictionary and tested them < Relationship operator. Although it is rare to compare two dictionary in this way; But you can do that if you need to.

This example then assigns dictionary 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, indicating that this is not a copy operation. To copy dictionary, use the copy() method. As you can see from the last few lines of this example, the copy is exactly the same as the original dictionary, but the variable that holds this dictionary has a different identifier.

When using dictionary in an Python program, you will most likely want to check whether dictionary contains specific keys or values. As shown in listing 8, these checks are easy to perform.
Listing 8. Conditional testing 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 membership of a key or data value in dictionary. 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 of keys or data values from the dictionary that were invoked, respectively.

Therefore, to determine whether a value is a key in dictionary, you should use the in operator to check that the value is in the list of key values returned by calling the keys() method. You can use a similar operation to check if a value is in the list of data values returned by calling the values() method. However, you can use the dictionary name as a shorthand notation. This makes sense because 1 would like to know if a data value (rather than a key value) is in dictionary.

In "Discover Python, Part 6," you saw how easy it is to loop through the elements in the container using for. The same technique 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 dictionary: using the Python iterator returned from the iterkeys(), itervalues(), or iteritems() methods. (by the way, you can check if these methods return an iterator instead of a container data type by calling the appropriate methods directly on dictionary, such as d.iterkeys ().) The iterkeys() method allows you to traverse the keys of dictionary, while the itervalues() method allows you to traverse the data values contained in dictionary. On the other hand, the iteritems() method allows simultaneous traversal of key-to-data value mappings.

dictionary: another powerful Python container

This article discussed the Python dictionary data type. dictionary is a heterogeneous, mutable container that relies on key-to-data value mapping (rather than a specific numeric order) to access elements in the container. It is easy to access, add, and remove elements from dictionary, and dictionary is easy to use for compound statements, such as if statements or for loops. All different types of data can be stored in dictionary and accessed by name or other composite key values, such as tuple, so Python dictionary enables developers to write concise and powerful programming statements.


Related articles: