Introduction to Python dictionary container

巴扎黑
Release: 2017-09-19 10:11:08
Original
1417 people have browsed it

Dictionary

We have all used a language dictionary to look up 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 (maps) definitions and other information with actual words. 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 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, a dictionary is a nice object, so even a novice programmer can easily use it in their own programs. Officially speaking, a dictionary in Python is a heterogeneous, mutable mapping container data type.

Creating a Dictionary

Previous articles in this series introduced some of the container data types in the Python programming language, including tuples, strings, and lists (see Resources). These containers are similar in that they are sequence-based. This means that elements in these collections are accessed based on their position in the sequence. So, given a sequence named a , you can access elements using either numeric indexes (like a[0] ) or fragments (like 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 index numbers, you use key values ​​to access elements in the collection. This means that constructing a dictionary container is a bit more complex than a tuple, string, or list because both the keys and the corresponding values ​​must be provided, as shown in Listing 1.

Listing 1. Creating 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
<type &#39;dict&#39;>
>>> d = {}      # Create an empty dictionary
>>> len(d)
>>> d = {1 : &#39;one&#39;} # Create a single item dictionary
>>> d
{1: &#39;one&#39;}
>>> len(d)
>>> d = {&#39;one&#39; : 1} # The key value can be non-numeric
>>> d
{&#39;one&#39;: 1}
>>> d = {&#39;one&#39;: [0, 1,2 , 3, 4, 5, 6, 7, 8, 9]}
>>> d
{&#39;one&#39;: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}
Copy after login

As shown in this example, creating a dictionary in Python uses curly braces and colon-separated keys - value combination. If no key-value combination is provided, an empty dictionary is created. Using a key-value combination creates a dictionary with one element, and so on, up to whatever size you need. As with any container type, you can find out the number of elements in the collection using the built-in len method.

The previous example also demonstrates another important issue about dictionary containers. The key is not limited to an integer; 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 a dictionary. But the values ​​in a dictionary can be of any data type.

Finally, this example illustrates that the underlying data type of a dictionary in Python is a dict object. To learn more about using dictionaries 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 on the dictionary(dictionary)

>>> help(dict)on class dict in module __builtin__:
   dict(object)
| dict() -> new empty dictionary.
| dict(mapping) -> new dictionary initialized from a mapping object&#39;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]
...
Copy after login

The help on the dict class points out that you can use the constructor to create a dictionary directly without using curly braces. Since more data must be provided when creating a dictionary than other container data types, it is not surprising that these creation methods are complex. However, it's not difficult to use a dictionary in practice, as shown in Listing 3.

Listing 3. Creating a 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&#39;t convert dictionary 
 update sequence element #0 to a sequence
  
>>> l = [(0, &#39;zero&#39;), (1, &#39;one&#39;), (2, &#39;two&#39;), (3, &#39;three&#39;)]
>>> d = dict(l)
>>> d
{0: &#39;zero&#39;, 1: &#39;one&#39;, 2: &#39;two&#39;, 3: &#39;three&#39;}
>>> l = [[0, &#39;zero&#39;], [1, &#39;one&#39;], [2, &#39;two&#39;], [3, &#39;three&#39;]]
>>> d
{0: &#39;zero&#39;, 1: &#39;one&#39;, 2: &#39;two&#39;, 3: &#39;three&#39;}
>>> d = dict(l)
>>> d
{0: &#39;zero&#39;, 1: &#39;one&#39;, 2: &#39;two&#39;, 3: &#39;three&#39;}
>>> d = dict(zero=0, one=1, two=2, three=3) 
>>> d
{&#39;zero&#39;: 0, &#39;three&#39;: 3, &#39;two&#39;: 2, &#39;one&#39;: 1}
>>> d = dict(0=zero, 1=one, 2=two, 3=three): keyword can&#39;t be an expression
Copy after login

As you can see, creating a dictionary requires key values ​​and data values. The first attempt to create a dictionary from the list fails because there are no matching key-data value pairs. The second and third examples demonstrate how to create a dictionary correctly: in the first case, use a list in which each element is a tuple; in the second case, also use a list, but each element in it is another list. In both cases, the inner container is used to obtain a mapping of keys to data values.

Another way to create a dict container directly is to directly provide a mapping of keys to data values. This technique allows keys and their corresponding values ​​to be explicitly defined. This method is actually less useful because the same task can be accomplished using curly braces. Also, as shown in the previous example, you cannot use numbers for keys when using this method, otherwise an exception will be thrown.

Accessing and modifying dictionary (dictionary)

After creating the dictionary, you need to access the data contained in it. Access is similar to accessing data in any Python container data type, as shown in Listing 4.

清单 4. 访问 dictionary 中的元素

>>> d = dict(zero=0, one=1, two=2, three=3)
>>> d
{&#39;zero&#39;: 0, &#39;three&#39;: 3, &#39;two&#39;: 2, &#39;one&#39;: 1}
>>> d[&#39;zero&#39;]
>>> d[&#39;three&#39;]
>>> d = {0: &#39;zero&#39;, 1: &#39;one&#39;, 2 : &#39;two&#39;, 3 : &#39;three&#39;, 4 : &#39;four&#39;, 5: &#39;five&#39;}
>>> d[0]
&#39;zero&#39;
>>> d[4]
&#39;four&#39;
>>> 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
Copy after login

可以看到,从字典(dictionary)中获取数据值的过程几乎与从任何容器类型中获取数据完全一样。在容器名后面的方括号中放上键值。当然,字典(dictionary)可以具有非数字的键值,如果您以前没有使用过这种数据类型,那么适应这一点需要些时间。因为在字典(dictionary)中次序是不重要的(dictionary 中数据的次序是任意的),所以可以对其他容器数据类型使用的片段功能,对于 字典(dictionary)是不可用的。试图使用片段或者试图从不存在的键访问数据就会抛出异常,指出相关的错误。

Python 中的字典(dictionary)容器也是易变的数据类型,这意味着在创建它之后可以修改它。如清单 5 所示,可以添加新的键到数据值的映射,可以修改现有的映射,还可以删除映射。

清单 5. 修改字典(dictionary)

>>> d = {0: &#39;zero&#39;, 1: &#39;one&#39;, 2: &#39;two&#39;, 3: &#39;three&#39;}
>>> d[0]
&#39;zero&#39;
>>> d[0] = &#39;Zero&#39;
>>> d
{0: &#39;Zero&#39;, 1: &#39;one&#39;, 2: &#39;two&#39;, 3: &#39;three&#39;}
>>> d[4] = &#39;four&#39;
>>> d[5] = &#39;five&#39;
>>> d
{0: &#39;Zero&#39;, 1: &#39;one&#39;, 2: &#39;two&#39;, 3: &#39;three&#39;, 4: &#39;four&#39;, 5: &#39;five&#39;}
>>> del d[0]
>>> d
{1: &#39;one&#39;, 2: &#39;two&#39;, 3: &#39;three&#39;, 4: &#39;four&#39;, 5: &#39;five&#39;}
>>> d[0] = &#39;zero&#39;
>>> d
{0: &#39;zero&#39;, 1: &#39;one&#39;, 2: &#39;two&#39;, 3: &#39;three&#39;, 4: &#39;four&#39;, 5: &#39;five&#39;}
Copy after login

清单 5 演示了几个重点。首先,修改数据值是很简单的:将新的值分配给适当的键。其次,添加新的键到数据值的映射也很简单:将相关数据分配给新的键值。Python 自动进行所有处理。不需要调用 append 这样的特殊方法。对于 dictionary 容器,次序是不重要的,所以这应该好理解,因为不是在字典(dictionary)后面附加映射,而是将它添加到容器中。最后,删除映射的办法是使用 del 操作符以及应该从容器中删除的键。

在清单 5 中有一个情况看起来有点儿怪,键值是按照数字次序显示的,而且这个次序与插入映射的次序相同。不要误解 —— 情况不总是这样的。Python 字典(dictionary)中映射的次序是任意的,对于不同的 Python 安装可能会有变化,甚至多次使用同一 Python 解释器运行相同代码也会有变化。如果在一个字典(dictionary)中使用不同类型的键和数据值,那么就很容易看出这一点,如清单 6 所示。

清单 6. 异构的容器

>>> d = {0: &#39;zero&#39;, &#39;one&#39;: 1}   
>>> d
{0: &#39;zero&#39;, &#39;one&#39;: 1}
>>> d[0]
&#39;zero&#39;
>>> type(d[0])
<type &#39;str&#39;>
>>> d[&#39;one&#39;]
>>> type(d[&#39;one&#39;])
<type &#39;int&#39;>
>>> d[&#39;two&#39;] = [0, 1, 2] 
>>> d
{0: &#39;zero&#39;, &#39;two&#39;: [0, 1, 2], &#39;one&#39;: 1}
>>> d[3] = (0, 1, 2, 3)
>>> d
{0: &#39;zero&#39;, 3: (0, 1, 2, 3), &#39;two&#39;: [0, 1, 2], &#39;one&#39;: 1}
>>> d[3] = &#39;a tuple&#39;
>>> d
{0: &#39;zero&#39;, 3: &#39;a tuple&#39;, &#39;two&#39;: [0, 1, 2], &#39;one&#39;: 1}
Copy after login

如这个例子所示,可以在一个字典(dictionary)中使用不同数据类型的键和数据值。还可以通过修改字典(dictionary)添加新的类型。最后,产生的 dictionary 的次序并不与插入数据的次序匹配。本质上,字典(dictionary)中元素的次序是由 Python 字典(dictionary)数据类型的实际实现控制的。新的 Python 解释器很容易改变这一次序,所以一定不要依赖于元素在字典(dictionary)中的特定次序。

用字典(dictionary)进行编程

作为正式的 Python 数据类型,字典(dictionary)支持其他较简单数据类型所支持的大多数操作。这些操作包括一般的关系操作符,比如 <、> 和 ==,如清单 7 所示。

清单 7. 一般关系操作符

>>> d1 = {0: &#39;zero&#39;}
>>> d2 = {&#39;zero&#39;:0}
>>> d1 < d2
>>> d2 = d1
>>> d1 < d2
>>> d1 == d2
>>> id(d1)
>>> id(d2)
>>> d2 = d1.copy()
>>> d1 == d2
>>> id(d1)
>>> id(d2)
Copy after login

前面的示例创建两个字典(dictionary)并使用它们测试 < 关系操作符。尽管很少以这种方式比较两个字典(dictionary);但是如果需要,可以这样做。

然后,这个示例将赋值给变量 d1 的字典(dictionary)赋值给另一个变量 d2。注意,内置的 id() 方法对于 d1 和 d2 返回相同的标识符值,这说明这不是复制操作。要想复制字典(dictionary) ,可以使用 copy() 方法。从这个示例中的最后几行可以看出,副本与原来的字典(dictionary)完全相同,但是容纳这字典(dictionary)的变量具有不同的标识符。

在 Python 程序中使用字典(dictionary)时,很可能希望检查字典(dictionary)中是否包含特定的键或值。如清单 8 所示,这些检查很容易执行。

清单 8. 条件测试和字典(dictionary)

>>> d = {0: &#39;zero&#39;, 3: &#39;a tuple&#39;, &#39;two&#39;: [0, 1, 2], &#39;one&#39;: 1}
>>> d.keys()
[0, 3, &#39;two&#39;, &#39;one&#39;]
>>> if 0 in d.keys():
...   print &#39;True&#39;
... 
>>> if &#39;one&#39; in d:
...   print &#39;True&#39;
... 
>>> if &#39;four&#39; in d:
...   print &#39;Dictionary contains four&#39;
... elif &#39;two&#39; in d:
...   print &#39;Dictionary contains two&#39;
... contains two
Copy after login

测试字典(dictionary)中键或数据值的成员关系是很简单的。dictionary 容器数据类型提供几个内置方法,包括 keys() 方法和 values() 方法(这里没有演示)。这些方法返回一个列表,其中分别包含进行调用的字典(dictionary)中的键或数据值。

因此,要判断某个值是否是字典(dictionary)中的键,应该使用 in 操作符检查这个值是否在调用 keys() 方法所返回的键值列表中。可以使用相似的操作检查某个值是否在调用 values() 方法所返回的数据值列表中。但是,可以使用字典(dictionary)名作为简写表示法。这是有意义的,因为一般希望知道某个数据值(而不是键值)是否在字典(dictionary)中。

在 “Discover Python, Part 6” 中,您看到了使用 for 循环遍历容器中的元素是多么容易。同样的技术也适用于 Python 字典(dictionary),如清单 9 所示。

清单 9. 迭代和字典(dictionary)

>>> d = {0: &#39;zero&#39;, 3: &#39;a tuple&#39;, &#39;two&#39;: [0, 1, 2], &#39;one&#39;: 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 &#39;d[&#39;,k,&#39;] = &#39;,v
... [ 0 ] = zero[ 3 ] = a tuple[ two ] = [0, 1, 2][ one ] = 1
Copy after login

这个示例演示了遍历字典(dictionary)的三种方式:使用从 iterkeys()、itervalues() 或 iteritems() 方法返回的 Python 迭代器。(顺便说一下,可以通过在字典(dictionary)上直接调用适当方法,比如 d.iterkeys(),从而检查这些方法是否返回一个迭代器而不是容器数据类型。)iterkeys() 方法允许遍历字典(dictionary)的键,而 itervalues() 方法允许遍历字典(dictionary)包含的数据值。另一方面,iteritems() 方法允许同时遍历键到数据值的映射。

字典(dictionary):另一种强大的 Python 容器

本文讨论了 Python 字典(dictionary)数据类型。字典(dictionary)是一种异构的、易变的容器,依赖键到数据值的映射(而不是特定的数字次序)来访问容器中的元素。访问、添加和删除字典(dictionary)中的元素都很简单,而且字典(dictionary)很容易用于复合语句,比如 if 语句或 for 循环。可以在字典(dictionary)中存储所有不同类型的数据,可以按照名称或其他复合键值(比如 tuple)访问这些数据,所以 Python 字典(dictionary)使开发人员能够编写简洁而又强大的编程语句。

The above is the detailed content of Introduction to Python dictionary container. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!