<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Python 字典 > 原文: [https://www.programiz.com/python-programming/dictionary](https://www.programiz.com/python-programming/dictionary) #### 在本教程中,您將學習有關 Python 字典的所有知識; 如何創建,訪問,添加,刪除元素以及各種內置方法。 Python 字典是無序的項目集合。 字典的每個項目都有一個鍵值對。 字典被優化以在鍵已知時檢索值。 * * * ## 創建 Python 字典 創建字典就像將項目放在用逗號分隔的大括號`{}`中一樣簡單。 項具有`key`和表示為一對的相應`value`(**鍵值**)。 雖然值可以是任何數據類型并且可以重復,但是鍵必須是不可變類型([字符串](/python-programming/string),[數字](/python-programming/numbers)或[元組](/python-programming/tuple)具有不可變元素)并且必須是唯一的。 ```py # empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = dict([(1,'apple'), (2,'ball')]) ``` 從上面可以看到,我們還可以使用內置的`dict()`函數創建字典。 * * * ## 從字典訪問元素 雖然索引與其他數據類型一起使用來訪問值,但是字典使用`keys`。 可以在方括號`[]`內或`get()`方法中使用鍵。 如果我們使用方括號`[]`,則在字典中找不到鍵的情況下會拋出`KeyError`。 另一方面,如果找不到鍵,則`get()`方法返回`None`。 ```py # get vs [] for retrieving elements my_dict = {'name': 'Jack', 'age': 26} # Output: Jack print(my_dict['name']) # Output: 26 print(my_dict.get('age')) # Trying to access keys which doesn't exist throws error # Output None print(my_dict.get('address')) # KeyError print(my_dict['address']) ``` **輸出** ```py Jack 26 None Traceback (most recent call last): File "<string>", line 15, in <module> print(my_dict['address']) KeyError: 'address' ``` * * * ## 更改和添加字典元素 字典是可變的。 我們可以使用賦值運算符添加新項或更改現有項的值。 如果鍵已經存在,那么現有值將被更新。 如果鍵不存在,則將新的**鍵值**對添加到字典中。 ```py # Changing and adding Dictionary Elements my_dict = {'name': 'Jack', 'age': 26} # update value my_dict['age'] = 27 #Output: {'age': 27, 'name': 'Jack'} print(my_dict) # add item my_dict['address'] = 'Downtown' # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'} print(my_dict) ``` **輸出**: ```py {'name': 'Jack', 'age': 27} {'name': 'Jack', 'age': 27, 'address': 'Downtown'} ``` * * * ## 從字典中刪除元素 我們可以使用`pop()`方法刪除字典中的特定項目。 此方法刪除提供了`key`的項目并返回`value`。 `popitem()`方法可用于從字典中刪除并返回任意的`(key, value)`項目對。 使用`clear()`方法可以一次刪除所有項目。 我們還可以使用`del`關鍵字刪除單個項目或整個字典本身。 ```py # Removing elements from a dictionary # create a dictionary squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # remove a particular item, returns its value # Output: 16 print(squares.pop(4)) # Output: {1: 1, 2: 4, 3: 9, 5: 25} print(squares) # remove an arbitrary item, return (key,value) # Output: (5, 25) print(squares.popitem()) # Output: {1: 1, 2: 4, 3: 9} print(squares) # remove all items squares.clear() # Output: {} print(squares) # delete the dictionary itself del squares # Throws Error print(squares) ``` **輸出**: ```py 16 {1: 1, 2: 4, 3: 9, 5: 25} (5, 25) {1: 1, 2: 4, 3: 9} {} Traceback (most recent call last): File "<string>", line 30, in <module> print(squares) NameError: name 'squares' is not defined ``` * * * ## Python 字典方法 下表列出了字典可用的方法。 在上面的示例中已經使用了其中一些。 | 方法 | 描述 | | --- | --- | | [`clear()`](/python-programming/methods/dictionary/clear) | 從字典中刪除所有項目。 | | [`copy()`](/python-programming/methods/dictionary/copy) | 返回字典的淺表副本。 | | [`fromkeys(seq[, v])`](/python-programming/methods/dictionary/fromkeys) | 返回一個新字典,其中的鍵從`seq`開始,其值等于`v`(默認為`None`)。 | | [`get(key [, d])`](/python-programming/methods/dictionary/get) | 返回`key`的值。 如果`key`不存在,則返回`d`(默認為`None`)。 | | [`items()`](/python-programming/methods/dictionary/items) | 以(鍵,值)格式返回字典項的新對象。 | | [`keys()`](/python-programming/methods/dictionary/keys) | 返回字典鍵的新對象。 | | [`pop(key [, d])`](/python-programming/methods/dictionary/pop) | 如果沒有找到`key`,則用`key`刪除該項目并返回其值或`d`。 如果未提供`d`,但未找到`key`,則它將彈出`KeyError`。 | | [`popitem()`](/python-programming/methods/dictionary/popitem) | 刪除并返回任意項(**鍵值**)。 如果字典為空,則拋出`KeyError`。 | | [`setdefault(key [, d])`](/python-programming/methods/dictionary/setdefault) | 如果`key`在字典中,則返回相應的值。 如果不是,則插入`key`,其值為`d`,然后返回`d`(默認為`None`)。 | | [`update([other])`](/python-programming/methods/dictionary/update) | 使用`other`中的鍵/值對更新字典,覆蓋現有鍵。 | | [`values()`](/python-programming/methods/dictionary/values) | 返回字典值的新對象 | 以下是這些方法的一些示例用例。 ```py # Dictionary Methods marks = {}.fromkeys(['Math', 'English', 'Science'], 0) # Output: {'English': 0, 'Math': 0, 'Science': 0} print(marks) for item in marks.items(): print(item) # Output: ['English', 'Math', 'Science'] print(list(sorted(marks.keys()))) ``` **輸出**: ```py {'Math': 0, 'English': 0, 'Science': 0} ('Math', 0) ('English', 0) ('Science', 0) ['English', 'Math', 'Science'] ``` * * * ## Python 字典推導式 字典推導式是一種用 Python 中的可迭代對象創建新字典的簡潔明了方法。 字典推導式由一個表達式對(**鍵值**)和大括號`{}`中的`for`語句組成。 這是制作字典的示例,其中每個項目都是一對數字及其平方。 ```py # Dictionary Comprehension squares = {x: x*x for x in range(6)} print(squares) ``` **輸出**: ```py {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} ``` 此代碼等效于 ```py squares = {} for x in range(6): squares[x] = x*x print(squares) ``` **輸出**: ```py {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} ``` 對于或[語句,字典推導式可以可選地包含更多](/python-programming/if-elif-else)[。](/python-programming/for-loop) 可選的`if`語句可以過濾出項以形成新字典。 以下是一些僅包含奇數項的字典的示例。 ```py # Dictionary Comprehension with if conditional odd_squares = {x: x*x for x in range(11) if x % 2 == 1} print(odd_squares) ``` **輸出**: ```py {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} ``` 要了解更多字典推導式,請訪問 [Python 字典推導式](/python-programming/dictionary-comprehension)。 * * * ## 其他字典操作 ### 字典成員資格測試 我們可以使用關鍵字`in`來測試`key`是否在字典中。 請注意,成員資格測試僅適用于`keys`,而不適用于`values`。 ```py # Membership Test for Dictionary Keys squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} # Output: True print(1 in squares) # Output: True print(2 not in squares) # membership tests for key only not value # Output: False print(49 in squares) ``` **輸出**: ```py True True False ``` ### 遍歷字典 我們可以使用`for`循環遍歷字典中的每個鍵。 ```py # Iterating through a Dictionary squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} for i in squares: print(squares[i]) ``` **輸出**: ```py 1 9 25 49 81 ``` * * * ### 字典內置函數 諸如`all()`,`any()`,`len()`,`cmp()`,`sorted()`等內置函數通常與字典一起使用以執行不同的任務。 | 函數 | 描述 | | --- | --- | | [`all()`](/python-programming/methods/built-in/all) | 如果字典的所有鍵均為`True`(或者字典為空),則返回`True`。 | | [`any()`](/python-programming/methods/built-in/any) | 如果字典的任何鍵為真,則返回`True`。 如果字典為空,則返回`False`。 | | [`len()`](/python-programming/methods/built-in/len) | 返回字典中的長度(項目數)。 | | `cmp()` | 比較兩個字典的項目。 (在 Python 3 中不可用) | | [`sorted()`](/python-programming/methods/built-in/sorted) | 返回字典中新排序的鍵列表。 | 以下是一些使用內置函數來處理字典的示例。 ```py # Dictionary Built-in Functions squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81} # Output: False print(all(squares)) # Output: True print(any(squares)) # Output: 6 print(len(squares)) # Output: [0, 1, 3, 5, 7, 9] print(sorted(squares)) ``` **輸出**: ```py False True 6 [0, 1, 3, 5, 7, 9] ```
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看