天天看點

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中的字典生成式