天天看点

python中的字典生成式_Python中的字典

python中的字典生成式

Python provides another composite data type called a dictionary, which is similar to a list in that it is a collection of objects.

Python提供了另一种称为字典的复合数据类型,它类似于列表,因为它是对象的集合。

Here’s what you’ll learn in this tutorial: You’ll cover the basic characteristics of Python dictionaries and learn how to access and manage dictionary data. Once you have finished this tutorial, you should have a good sense of when a dictionary is the appropriate data type to use, and how to do so.

这是在本教程中您将学到的内容:您将介绍Python字典的基本特征,并学习如何访问和管理字典数据。 学完本教程后,您应该对何时使用字典是合适的数据类型以及如何使用字典有很好的了解。

Dictionaries and lists share the following characteristics:

词典和列表具有以下特征:

  • Both are mutable.
  • Both are dynamic. They can grow and shrink as needed.
  • Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.
  • 两者都是可变的。
  • 两者都是动态的。 它们可以根据需要增长和收缩。
  • 两者都可以嵌套。 一个列表可以包含另一个列表。 一个词典可以包含另一个词典。 字典也可以包含列表,反之亦然。

Dictionaries differ from lists in two important ways. The first is the ordering of the elements:

字典与列表在两个重要方面有所不同。 首先是元素的顺序:

  • Elements in a list have a distinct order, which is an intrinsic property of that list.
  • Dictionaries are unordered. Elements are not kept in any specific order.
  • 列表中的元素具有不同的顺序,这是该列表的固有属性。
  • 字典是无序的。 元素不按任何特定顺序保留。

The second difference lies in how elements are accessed:

第二个区别在于元素的访问方式:

  • List elements are accessed by their position in the list, via indexing.
  • Dictionary elements are accessed via keys.
  • 列表元素通过索引在列表中的位置进行访问。
  • 字典元素可通过键访问。

定义字典 (Defining a Dictionary)

Dictionaries are Python’s implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.

字典是Python对数据结构的一种实现,这种结构通常被称为关联数组。 字典由键值对的集合组成。 每个键值对将键映射到其关联值。

You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces (

{}

). A colon (

:

) separates each key from its associated value:

您可以通过用大括号(

{}

)括起来的键值对列表的逗号分隔列表来定义字典。 冒号(

:

)分隔从其关联的值的每个键:

d d = = {
    {
    << keykey >> : : << valuevalue >> ,
    ,
    << keykey >> : : << valuevalue >> ,
      ,
      .
      .
      .
      .
      .
    .
    << keykey >> : : << valuevalue >
>
}
}
           

The following defines a dictionary that maps a location to the name of its corresponding Major League Baseball team:

下面定义了一个字典,该字典将位置映射到其相应的美国职棒大联盟球队的名称:

python中的字典生成式_Python中的字典

Dictionary Mapping Location to MLB Team 词典将位置映射到MLB团队

You can also construct a dictionary with the built-in

dict()

function. The argument to

dict()

should be a sequence of key-value pairs. A list of tuples works well for this:

您也可以使用内置的

dict()

函数构造字典。

dict()

的参数应该是键值对的序列。 元组列表很适合此操作:

d d = = dictdict ([
    ([
    (( << keykey >> , , << valuevalue >> ),
    ),
    (( << keykey >> , , << valuevalue ),
      ),
      .
      .
      .
      .
      .
    .
    (( << keykey >> , , << valuevalue >> )
)
])
])
           

MLB_team

can then also be defined this way:

然后,也可以通过以下方式定义

MLB_team

If the key values are simple strings, they can be specified as keyword arguments. So here is yet another way to define

MLB_team

:

如果键值是简单字符串,则可以将它们指定为关键字参数。 因此,这是定义

MLB_team

另一种方法:

>>> >>>  MLB_team MLB_team = = dictdict (
(
...     ...     ColoradoColorado == 'Rockies''Rockies' ,
,
...     ...     BostonBoston == 'Red Sox''Red Sox' ,
,
...     ...     MinnesotaMinnesota == 'Twins''Twins' ,
,
...     ...     MilwaukeeMilwaukee == 'Brewers''Brewers' ,
,
...     ...     SeattleSeattle == 'Mariners'
'Mariners'
... ...  )
)
           

Once you’ve defined a dictionary, you can display its contents, the same as you can do for a list. All three of the definitions shown above appear as follows when displayed:

定义字典后,就可以显示其内容,就像对列表一样。 显示时,上面显示的所有三个定义如下所示:

It may seem as though the order in which the key-value pairs are displayed has significance, but remember that dictionaries are unordered collections. They have to print out in some order, of course, but it is effectively random. In the example above, it’s not even the same order in which they were defined.

键值对的显示顺序似乎很有意义,但请记住,字典是无序集合。 当然,它们必须按一定顺序打印,但这实际上是随机的。 在上面的示例中,定义它们的顺序甚至都不相同。

As you add or delete entries, you won’t be guaranteed that any sort of order will be maintained. But that doesn’t matter, because you don’t access dictionary entries by numerical index:

添加或删除条目时,不能保证将维持任何顺序。 但这没关系,因为您不按数字索引访问字典条目:

>>> >>>  MLB_teamMLB_team [[ 11 ]
]
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#13>", line "<pyshell#13>" , line 1, in 1 , in <module>
    <module>
    MLB_teamMLB_team [[ 11 ]
]
KeyError: KeyError : 1
1
           

访问字典值 (Accessing Dictionary Values)

Of course, dictionary elements must be accessible somehow. If you don’t get them by index, then how do you get them?

当然,字典元素必须以某种方式可访问。 如果您没有按索引获取它们,那么如何获取它们呢?

A value is retrieved from a dictionary by specifying its corresponding key in square brackets (

[]

):

通过在方括号(

[]

)中指定其对应的键,可以从字典中检索一个值:

If you refer to a key that is not in the dictionary, Python raises an exception:

如果您引用的字典中没有键,Python会引发异常:

>>> >>>  MLB_teamMLB_team [[ 'Toronto''Toronto' ]
]
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#19>", line "<pyshell#19>" , line 1, in 1 , in <module>
    <module>
    MLB_teamMLB_team [[ 'Toronto''Toronto' ]
]
KeyError: KeyError : 'Toronto'
'Toronto'
           

Adding an entry to an existing dictionary is simply a matter of assigning a new key and value:

向现有字典中添加条目仅是分配新键和值的问题:

If you want to update an entry, you can just assign a new value to an existing key:

如果要更新条目,则可以为现有键分配一个新值:

>>> >>>  MLB_teamMLB_team [[ 'Seattle''Seattle' ] ] = = 'Seahawks'
'Seahawks'
>>> >>>  MLB_team
MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Milwaukee': 'Brewers',
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Milwaukee': 'Brewers',
'Seattle': 'Seahawks', 'Minnesota': 'Twins', 'Kansas City': 'Royals'}
'Seattle': 'Seahawks', 'Minnesota': 'Twins', 'Kansas City': 'Royals'}
           

To delete an entry, use the

del

statement, specifying the key to delete:

要删除条目,请使用

del

语句,并指定要删除的键:

Begone, Seahawks! Thou art an NFL team.

贝格尼,海鹰! 您是NFL球队。

字典键与列表索引 (Dictionary Keys vs. List Indices)

You may have noticed that the interpreter raises the same exception,

KeyError

, when a dictionary is accessed with either an undefined key or by a numeric index:

您可能已经注意到,当使用未定义的键或通过数字索引访问字典时,解释器会引发相同的异常

KeyError

>>> >>>  MLB_teamMLB_team [[ 'Toronto''Toronto' ]
]
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#8>", line "<pyshell#8>" , line 1, in 1 , in <module>
    <module>
    MLB_teamMLB_team [[ 'Toronto''Toronto' ]
]
KeyError: KeyError : 'Toronto'

'Toronto'

>>> >>>  MLB_teamMLB_team [[ 11 ]
]
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#9>", line "<pyshell#9>" , line 1, in 1 , in <module>
    <module>
    MLB_teamMLB_team [[ 11 ]
]
KeyError: KeyError : 1
1
           

In fact, it’s the same error. In the latter case,

[1]

looks like a numerical index, but it isn’t.

实际上,这是相同的错误。 在后一种情况下,

[1]

看起来像数字索引,但事实并非如此。

You will see later in this tutorial that an object of any immutable type can be used as a dictionary key. Accordingly, there is no reason you can’t use integers:

您将在本教程的后面部分看到,任何不可变类型的对象都可以用作字典键。 因此,没有理由不能使用整数:

In the expressions

MLB_team[1]

,

d[0]

, and

d[2]

, the numbers in square brackets appear as though they might be indices. But Python is interpreting them as dictionary keys. You can’t be guaranteed that Python will maintain dictionary objects in any particular order, and you can’t access them by numerical index. The syntax may look similar, but you can’t treat a dictionary like a list:

在表达式

MLB_team[1]

d[0]

d[2]

,方括号中的数字似乎好像是索引。 但是Python会将它们解释为字典键。 您不能保证Python将以任何特定顺序维护字典对象,并且不能通过数字索引访问它们。 语法可能看起来相似,但是您不能将字典像列表一样对待:

>>> >>>  typetype (( dd )
)
<class 'dict'>

<class 'dict'>

>>> >>>  dd [[ -- 11 ]
]
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#30>", line "<pyshell#30>" , line 1, in 1 , in <module>
    <module>
    dd [[ -- 11 ]
]
KeyError: KeyError : -1

-1

>>> >>>  dd [[ 00 :: 22 ]
]
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#31>", line "<pyshell#31>" , line 1, in 1 , in <module>
    <module>
    dd [[ 00 :: 22 ]
]
TypeError: TypeError : unhashable type: 'slice'

unhashable type: 'slice'

>>> >>>  dd .. appendappend (( 'e''e' )
)
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#32>", line "<pyshell#32>" , line 1, in 1 , in <module>
    <module>
    dd .. appendappend (( 'e''e' )
)
AttributeError: AttributeError : 'dict' object has no attribute 'append'
'dict' object has no attribute 'append'
           

逐步建立字典 (Building a Dictionary Incrementally)

Defining a dictionary using curly braces and a list of key-value pairs, as shown above, is fine if you know all the keys and values in advance. But what if you want to build a dictionary on the fly?

如果您事先知道所有键和值,则使用大括号和键-值对列表定义字典,如上所示。 但是,如果您想即时建立字典怎么办?

You can start by creating an empty dictionary, which is specified by empty curly braces. Then you can add new keys and values one at a time:

您可以从创建一个空的字典开始,该字典由空的花括号指定。 然后,您可以一次添加一个新的键和值:

Once the dictionary is created in this way, its values are accessed the same way as any other dictionary:

以这种方式创建字典后,其值的访问方式与任何其他字典相同:

>>> >>>  person
person
{'fname': 'Joe', 'lname': 'Fonebone', 'age': 51, 'spouse': 'Edna',
{'fname': 'Joe', 'lname': 'Fonebone', 'age': 51, 'spouse': 'Edna',
'children': ['Ralph', 'Betty', 'Joey'], 'pets': {'dog': 'Fido', 'cat': 'Sox'}}

'children': ['Ralph', 'Betty', 'Joey'], 'pets': {'dog': 'Fido', 'cat': 'Sox'}}

>>> >>>  personperson [[ 'fname''fname' ]
]
'Joe'
'Joe'
>>> >>>  personperson [[ 'age''age' ]
]
51
51
>>> >>>  personperson [[ 'children''children' ]
]
['Ralph', 'Betty', 'Joey']
['Ralph', 'Betty', 'Joey']
           

Retrieving the values in the sublist or subdictionary requires an additional index or key:

检索子列表或子词典中的值需要附加索引或键:

This example exhibits another feature of dictionaries: the values contained in the dictionary don’t need to be the same type. In

person

, some of the values are strings, one is an integer, one is a list, and one is another dictionary.

此示例展示了词典的另一个功能:词典中包含的值不必是同一类型。 就

person

,其中一些值是字符串,一个是整数,一个是列表,一个是另一本字典。

Just as the values in a dictionary don’t need to be of the same type, the keys don’t either:

就像字典中的值不需要是同一类型一样,键也不需要:

>>> >>>  foo foo = = {{ 4242 : : 'aaa''aaa' , , 2.782.78 : : 'bbb''bbb' , , TrueTrue : : 'ccc''ccc' }
}
>>> >>>  foo
foo
{42: 'aaa', 2.78: 'bbb', True: 'ccc'}
{42: 'aaa', 2.78: 'bbb', True: 'ccc'}
>>> >>>  foofoo [[ 4242 ]
]
'aaa'
'aaa'
>>> >>>  foofoo [[ 2.782.78 ]
]
'bbb'
'bbb'
>>> >>>  foofoo [[ TrueTrue ]
]
'ccc'
'ccc'
           

Here, one of the keys is an integer, one is a float, and one is a Boolean. It’s not obvious how this would be useful, but you never know.

在这里,键之一是整数,一个是浮点数,一个是布尔值。 目前尚不清楚这将如何有用,但您永远不会知道。

Notice how versatile Python dictionaries are. In

MLB_team

, the same piece of information (the baseball team name) is kept for each of several different geographical locations.

person

, on the other hand, stores varying types of data for a single person.

请注意,Python字典的用途广泛。 在

MLB_team

,为多个不同地理位置中的每一个保留相同的信息(棒球队名称)。

person

,在另一方面,存储不同类型的数据的单个人。

You can use dictionaries for a wide range of purposes because there are so few limitations on the keys and values that are allowed. But there are some. Read on!

您可以将字典用于多种用途,因为所允许的键和值的限制很少。 但是有一些。 继续阅读!

字典键限制 (Restrictions on Dictionary Keys)

Almost any type of value can be used as a dictionary key in Python. You just saw this example, where integer, float, and Boolean objects are used as keys:

在Python中,几乎任何类型的值都可以用作字典键。 您刚刚看到了这个示例,其中整数,浮点和布尔对象用作键:

You can even use built-in objects like types and functions:

您甚至可以使用内置对象,例如类型和函数:

>>> >>>  d d = = {{ intint : : 11 , , floatfloat : : 22 , , boolbool : : 33 }
}
>>> >>>  d
d
{<class 'int'>: 1, <class 'float'>: 2, <class 'bool'>: 3}
{<class 'int'>: 1, <class 'float'>: 2, <class 'bool'>: 3}
>>> >>>  dd [[ floatfloat ]
]
2

2

>>> >>>  d d = = {{ binbin : : 11 , , hexhex : : 22 , , octoct : : 33 }
}
>>> >>>  dd [[ octoct ]
]
3
3
           

However, there are a couple restrictions that dictionary keys must abide by.

但是,字典键必须遵守几个限制。

First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn’t make sense to map a particular key more than once.

首先,给定的键只能在字典中出现一次。 不允许重复的密钥。 字典将每个键映射到相应的值,因此多次映射一个特定的键没有意义。

You saw above that when you assign a value to an already existing dictionary key, it does not add the key a second time, but replaces the existing value:

您在上面看到了,当您为一个现有的字典键分配一个值时,它不会第二次添加该键,而是替换现有的值:

Similarly, if you specify a key a second time during the initial creation of a dictionary, the second occurrence will override the first:

同样,如果您在最初创建字典的过程中第二次指定键,则第二次出现将覆盖第一个:

>>> >>>  MLB_team MLB_team = = {
{
...     ...     'Colorado' 'Colorado' : : 'Rockies''Rockies' ,
,
...     ...     'Boston'   'Boston'   : : 'Red Sox''Red Sox' ,
,
...     ...     'Minnesota''Minnesota' : : 'Timberwolves''Timberwolves' ,
,
...     ...     'Milwaukee''Milwaukee' : : 'Brewers''Brewers' ,
,
...     ...     'Seattle'  'Seattle'  : : 'Mariners''Mariners' ,
,
...     ...     'Minnesota''Minnesota' : : 'Twins'
'Twins'
... ...  }
}
>>> >>>  MLB_team
MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Mariners'}
'Milwaukee': 'Brewers', 'Seattle': 'Mariners'}
           

Begone, Timberwolves! Thou art an NBA team. Sort of.

贝戈恩,森林狼! 您是一支NBA球队。 有点。

Secondly, a dictionary key must be of a type that is immutable. That means an integer, float, string, or Boolean can be a dictionary key, as you have seen above. A tuple can also be a dictionary key, because tuples are immutable:

其次,字典键必须是不可变的类型。 正如上面所看到的,这意味着整数,浮点数,字符串或布尔值可以是字典键。 元组也可以是字典键,因为元组是不可变的:

Recall from the discussion on tuples that one rationale for using a tuple instead of a list is that there are circumstances where an immutable type is required. This is one of them.

回顾关于元组的讨论,使用元组而不是列表的一个基本原理是在某些情况下需要不可变的类型。 这就是其中之一。

However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable:

但是,列表和其他字典都不能用作字典键,因为列表和字典是可变的:

>>> >>>  d d = = {[{[ 11 , , 11 ]: ]: 'a''a' , , [[ 11 , , 22 ]: ]: 'b''b' , , [[ 22 , , 11 ]: ]: 'c''c' , , [[ 22 , , 22 ]: ]: 'd''d' }
}
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#20>", line "<pyshell#20>" , line 1, in 1 , in <module>
    <module>
    d d = = {[{[ 11 , , 11 ]: ]: 'a''a' , , [[ 11 , , 22 ]: ]: 'b''b' , , [[ 22 , , 11 ]: ]: 'c''c' , , [[ 22 , , 22 ]: ]: 'd''d' }
}
TypeError: TypeError : unhashable type: 'list'
unhashable type: 'list'
           

Technical Note: Why does the error message say “unhashable” rather than “mutable”? Python uses hash values internally to implement dictionary keys, so an object must be hashable to be used as a key.

技术说明:为什么错误消息显示“无法散列”而不是“可变”? Python内部使用哈希值来实现字典键,因此对象必须是可哈希的才能用作键。

See the Python Glossary for more information.

有关更多信息,请参见Python词汇表 。

字典值限制 (Restrictions on Dictionary Values)

By contrast, there are no restrictions on dictionary values. Literally none at all. A dictionary value can be any type of object Python supports, including mutable types like lists and dictionaries, and user-defined objects, which you will learn about in upcoming tutorials.

相比之下,字典值没有限制。 从字面上看完全没有。 字典值可以是Python支持的任何类型的对象,包括诸如列表和字典之类的可变类型以及用户定义的对象,您将在接下来的教程中学习这些类型。

There is also no restriction against a particular value appearing in a dictionary multiple times:

对于在字典中多次出现的特定值也没有限制:

运算符和内置函数 (Operators and Built-in Functions)

You have already become familiar with many of the operators and built-in functions that can be used with strings, lists, and tuples. Some of these work with dictionaries as well.

您已经熟悉许多可用于字符串 , 列表和元组的运算符和内置函数。 其中一些还可以和字典一起使用。

For example, the

in

and

not in

operators return

True

or

False

according to whether the specified operand occurs as a key in the dictionary:

例如,

in

not in

运算符根据指定的操作数是否作为字典中的键出现而返回

True

False

>>> >>>  MLB_team MLB_team = = {
{
...     ...     'Colorado' 'Colorado' : : 'Rockies''Rockies' ,
,
...     ...     'Boston'   'Boston'   : : 'Red Sox''Red Sox' ,
,
...     ...     'Minnesota''Minnesota' : : 'Twins''Twins' ,
,
...     ...     'Milwaukee''Milwaukee' : : 'Brewers''Brewers' ,
,
...     ...     'Seattle'  'Seattle'  : : 'Mariners'
'Mariners'
... ...  }

}

>>> >>>  'Milwaukee' 'Milwaukee' in in MLB_team
MLB_team
True
True
>>> >>>  'Toronto' 'Toronto' in in MLB_team
MLB_team
False
False
>>> >>>  'Toronto' 'Toronto' not not in in MLB_team
MLB_team
True
True
           

You can use the

in

operator together with short-circuit evaluation to avoid raising an error when trying to access a key that is not in the dictionary:

您可以将

in

运算符与短路评估结合使用,以避免在尝试访问不在词典中的键时引发错误:

In the second case, due to short-circuit evaluation, the expression

MLB_team['Toronto']

is not evaluated, so the

KeyError

exception does not occur.

在第二种情况下,由于短路评估,不评估表达式

MLB_team['Toronto']

,因此不会发生

KeyError

异常。

The

len()

function returns the number of key-value pairs in a dictionary:

len()

函数返回字典中键/值对的数量:

>>> >>>  MLB_team MLB_team = = {
{
...     ...     'Colorado' 'Colorado' : : 'Rockies''Rockies' ,
,
...     ...     'Boston'   'Boston'   : : 'Red Sox''Red Sox' ,
,
...     ...     'Minnesota''Minnesota' : : 'Twins''Twins' ,
,
...     ...     'Milwaukee''Milwaukee' : : 'Brewers''Brewers' ,
,
...     ...     'Seattle'  'Seattle'  : : 'Mariners'
'Mariners'
... ...  }
}
>>> >>>  lenlen (( MLB_teamMLB_team )
)
5
5
           

内置词典方法 (Built-in Dictionary Methods)

As with strings and lists, there are several built-in methods that can be invoked on dictionaries. In fact, in some cases, the list and dictionary methods share the same name. (In the discussion on object-oriented programming, you will see that it is perfectly acceptable for different types to have methods with the same name.)

与字符串和列表一样,可以在字典上调用几种内置方法。 实际上,在某些情况下,列表和字典方法使用相同的名称。 (在有关面向对象编程的讨论中,您将看到,对于具有不同名称的方法,不同类型完全可以接受。)

The following is an overview of methods that apply to dictionaries:

以下是适用于词典的方法的概述:

d.clear()

d.clear()

Clears a dictionary.

清除字典。

d.clear()

empties dictionary

d

of all key-value pairs:

d.clear()

清空所有键值对的字典

d

d.get(<key>[, <default>])

d.get(<key>[, <default>])

Returns the value for a key if it exists in the dictionary.

如果字典中存在键,则返回该键的值。

The

.get()

method provides a convenient way of getting the value of a key from a dictionary without checking ahead of time whether the key exists, and without raising an error.

.get()

方法提供了一种从字典中获取键值的便捷方法,而无需提前检查键是否存在,也不会引发错误。

d.get(<key>)

searches dictionary

d

for

<key>

and returns the associated value if it is found. If

<key>

is not found, it returns

None

:

d.get(<key>)

字典

d

搜索

<key>

并返回找到的关联值。 如果未找到

<key>

,则返回

None

>>> >>>  d d = = {{ 'a''a' : : 1010 , , 'b''b' : : 2020 , , 'c''c' : : 3030 }

}

>>> >>>  printprint (( dd .. getget (( 'b''b' ))
))
20
20
>>> >>>  printprint (( dd .. getget (( 'z''z' ))
))
None
None
           

If

<key>

is not found and the optional

<default>

argument is specified, that value is returned instead of

None

:

如果未找到

<key>

并指定了可选的

<default>

参数,则返回该值而不是

None

d.items()

d.items()

Returns a list of key-value pairs in a dictionary.

返回字典中的键值对列表。

d.items()

returns a list of tuples containing the key-value pairs in

d

. The first item in each tuple is the key, and the second item is the key’s value:

d.items()

返回包含

d

中的键值对的元组列表。 每个元组中的第一项是键,第二项是键的值:

>>> >>>  d d = = {{ 'a''a' : : 1010 , , 'b''b' : : 2020 , , 'c''c' : : 3030 }
}
>>> >>>  d
d
{'a': 10, 'b': 20, 'c': 30}

{'a': 10, 'b': 20, 'c': 30}

>>> >>>  listlist (( dd .. itemsitems ())
())
[('a', 10), ('b', 20), ('c', 30)]
[('a', 10), ('b', 20), ('c', 30)]
>>> >>>  listlist (( dd .. itemsitems ())[())[ 11 ][][ 00 ]
]
'b'
'b'
>>> >>>  listlist (( dd .. itemsitems ())[())[ 11 ][][ 11 ]
]
20
20
           

d.keys()

d.keys()

Returns a list of keys in a dictionary.

返回字典中的键列表。

d.keys()

returns a list of all keys in

d

:

d.keys()

返回

d

中所有键的列表:

d.values()

d.values()

Returns a list of values in a dictionary.

返回字典中的值列表。

d.values()

returns a list of all values in

d

:

d.values()

返回

d

中所有值的列表:

>>> >>>  d d = = {{ 'a''a' : : 1010 , , 'b''b' : : 2020 , , 'c''c' : : 3030 }
}
>>> >>>  d
d
{'a': 10, 'b': 20, 'c': 30}

{'a': 10, 'b': 20, 'c': 30}

>>> >>>  listlist (( dd .. valuesvalues ())
())
[10, 20, 30]
[10, 20, 30]
           

Any duplicate values in

d

will be returned as many times as they occur:

d

任何重复值将返回它们出现的次数:

Technical Note: The

.items()

,

.keys()

, and

.values()

methods actually return something called a view object. A dictionary view object is more or less like a window on the keys and values. For practical purposes, you can think of these methods as returning lists of the dictionary’s keys and values.

技术说明:

.items()

.keys()

.values()

方法实际上返回的东西称为视图对象 。 字典视图对象或多或少像键和值上的窗口。 出于实际目的,您可以将这些方法视为返回字典键和值的列表。

d.pop(<key>[, <default>])

d.pop(<key>[, <default>])

Removes a key from a dictionary, if it is present, and returns its value.

从字典中删除键(如果存在),并返回其值。

If

<key>

is present in

d

,

d.pop(<key>)

removes

<key>

and returns its associated value:

如果

d

存在

<key>

,则

d.pop(<key>)

将删除

<key>

并返回其关联值:

>>> >>>  d d = = {{ 'a''a' : : 1010 , , 'b''b' : : 2020 , , 'c''c' : : 3030 }

}

>>> >>>  dd .. poppop (( 'b''b' )
)
20
20
>>> >>>  d
d
{'a': 10, 'c': 30}
{'a': 10, 'c': 30}
           

d.pop(<key>)

raises a

KeyError

exception if

<key>

is not in

d

:

d.pop(<key>)

提出了一个

KeyError

异常,如果

<key>

不在

d

If

<key>

is not in

d

, and the optional

<default>

argument is specified, then that value is returned, and no exception is raised:

如果

<key>

不在

d

,并且指定了可选的

<default>

参数,则将返回该值,并且不会引发异常:

>>> >>>  d d = = {{ 'a''a' : : 1010 , , 'b''b' : : 2020 , , 'c''c' : : 3030 }
}
>>> >>>  dd .. poppop (( 'z''z' , , -- 11 )
)
-1
-1
>>> >>>  d
d
{'a': 10, 'b': 20, 'c': 30}
{'a': 10, 'b': 20, 'c': 30}
           

d.popitem()

d.popitem()

Removes a key-value pair from a dictionary.

从字典中删除键/值对。

d.popitem()

removes a random, arbitrary key-value pair from

d

and returns it as a tuple:

d.popitem()

d

删除一个随机的,任意键-值对,并将其作为元组返回:

If

d

is empty,

d.popitem()

raises a

KeyError

exception:

如果

d

是空的,

d.popitem()

提出了一个

KeyError

例外:

>>> >>>  d d = = {}
{}
>>> >>>  dd .. popitempopitem ()
()
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#11>", line "<pyshell#11>" , line 1, in 1 , in <module>
    <module>
    dd .. popitempopitem ()
()
KeyError: KeyError : 'popitem(): dictionary is empty'
'popitem(): dictionary is empty'
           

d.update(<obj>)

d.update(<obj>)

Merges a dictionary with another dictionary or with an iterable of key-value pairs.

将一个字典与另一个字典或可迭代的键-值对合并。

If

<obj>

is a dictionary,

d.update(<obj>)

merges the entries from

<obj>

into

d

. For each key in

<obj>

:

如果

<obj>

是一个字典,

d.update(<obj>)

合并的条目从

<obj>

d

。 对于

<obj>

每个键:

  • If the key is not present in

    d

    , the key-value pair from

    <obj>

    is added to

    d

    .
  • If the key is already present in

    d

    , the corresponding value in

    d

    for that key is updated to the value from

    <obj>

    .
  • 如果

    d

    不存在键,则将

    <obj>

    的键值对添加到

    d

  • 如果

    d

    已经存在该键,则

    d

    与该键对应的值将更新为

    <obj>

    的值。

Here is an example showing two dictionaries merged together:

这是显示两个词典合并在一起的示例:

In this example, key

'b'

already exists in

d1

, so its value is updated to

200

, the value for that key from

d2

. However, there is no key

'd'

in

d1

, so that key-value pair is added from

d2

.

在此示例中,键

'b'

已存在于

d1

,因此其值更新为

200

,该键的值从

d2

。 但是,在

d1

没有键

'd'

,因此从

d2

添加了键值对。

<obj>

may also be a sequence of key-value pairs, similar to when the

dict()

function is used to define a dictionary. For example,

<obj>

can be specified as a list of tuples:

<obj>

也可以是键值对的序列,类似于使用

dict()

函数定义字典时。 例如,可以将

<obj>

指定为元组列表:

>>> >>>  d1 d1 = = {{ 'a''a' : : 1010 , , 'b''b' : : 2020 , , 'c''c' : : 3030 }
}
>>> >>>  d1d1 .. updateupdate ([(([( 'b''b' , , 200200 ), ), (( 'd''d' , , 400400 )])
)])
>>> >>>  d1
d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}
{'a': 10, 'b': 200, 'c': 30, 'd': 400}
           

Or the values to merge can be specified as a list of keyword arguments:

或者可以将要合并的值指定为关键字参数列表:

结论 (Conclusion)

In this tutorial, you covered the basic properties of the Python dictionary and learned how to access and manipulate dictionary data.

在本教程中,您介绍了Python 词典的基本属性,并学习了如何访问和操作词典数据。

Lists and dictionaries are two of the most frequently used Python types. As you have seen, they differ from one another in the following ways:

列表和字典是两种最常用的Python类型。 如您所见,它们在以下方面彼此不同:

Type 类型 Element Order 元素顺序 Element Access 元素访问
List 清单 Ordered 已订购 By index 按索引
Dictionary 字典 Unordered 无序 By key 按键

Because of their differences, lists and dictionaries tend to be appropriate for different circumstances. You should now have a good feel for which, if either, would be best for a given situation.

由于它们的差异,列表和字典往往适合于不同的情况。 现在,您应该有一个良好的感觉,如果有的话,这将是给定情况下的最佳选择。

Next you will learn about Python sets. The set is another unordered composite data type, but it is quite different from a dictionary.

接下来,您将了解Python 集 。 该集合是另一种无序的复合数据类型,但与字典有很大不同。

翻译自: https://www.pybloggers.com/2018/08/dictionaries-in-python/

python中的字典生成式