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

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Python 字典 > 原文: [https://javabeginnerstutorial.com/python-tutorial/python3-dictionary-2/](https://javabeginnerstutorial.com/python-tutorial/python3-dictionary-2/) 在上一篇文章中,我們討論了 [Python 列表](https://javabeginnerstutorial.com/python-tutorial/python-list-2/)。 在這里,我將向您詳細介紹 Python 字典。 字典是 Python 中的鍵值存儲。 由于像哈希表這樣的實現,并且鍵必須唯一,因此它們使對元素的快速訪問成為可能。 鍵和值之間用冒號(`:`)分隔,整個字典在花括號(`{}`)之間定義。 ## 創建字典和訪問元素 將創建一個空的字典,其中包含大括號和右括號: ```py >>> d = {} >>> type(d) <class 'dict'> ``` 要擁有帶有值的字典,我們必須在這些花括號之間添加鍵-值對。 鍵具有與`set`元素相同的限制:它們必須是可哈希的,因此不允許使用列表,字典,集合,而只能使用不可變的值,例如數字,字符串,布爾值,元組和`Frozensets`。 ```py >>> d = {'name':'Gabor', 'age':31} >>> d {'name': 'Gabor', 'age': 31} ``` 自然,您可以像真正的字典一樣使用字典變量。 例如,您可以創建英語-德語詞典來“翻譯”一些單詞。 ```py >>> en_de = {'eggs':'Eier', 'sausage':'Würstchen','bacon':'Schinken', 'spam':'Spam'} >>> en_de {'bacon': 'Schinken', 'sausage': 'Würstchen', 'eggs': 'Eier', 'spam': 'Spam'} >>> en_de['eggs'] 'Eier' >>> en_de['baked beans'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'baked beans' >>> en_de.get('baked beans','unknown') 'unknown' ``` 如您在上面看到的,訪問元素可以通過它們的鍵來完成(例如示例中的`en_de['eggs']`),但是,如果 python 詞典中不存在鍵,則會出現`KeyError`。 自然,可以通過使用`get`方法來避免`KeyError`,該方法接受可選的默認值。 如果未提供可選的默認值,則如果字典中不存在該鍵,則返回`None`: ```py >>> bb = en_de.get('baked beans') >>> print(bb) None ``` 如果您有兩個列表,則可能需要將它們合并為對列表(最終是鍵值對)。 您可以使用`zip`函數執行此操作。 之后,您可以將此壓縮列表轉換為字典,其中每對的第一個元素將是鍵,而對的第二個元素將是值。 ```py >>> food = ['eggs', 'sausage','bacon','spam'] >>> preferences = ['yes','no','yes','no'] >>> food_preferences = dict(zip(food, preferences)) >>> food_preferences {'bacon': 'yes', 'sausage': 'no', 'eggs': 'yes', 'spam': 'no'} ``` 正如您在上面看到的那樣,這是將兩個列表轉換成字典的一種精致且 Pythonic 的方式。 ## 添加和刪??除元素 當然,您可以在字典中添加元素或從中刪除元素。 方法與我們從列表中學到的方法完全相同,但讓我們通過示例進行查看。 ```py >>> d = {'eggs':2} >>> >>> d {'eggs': 2} >>> d['bacon'] = 1 >>> d {'bacon': 1, 'eggs': 2} >>> d.update({'spam':0}) >>> d {'bacon': 1, 'eggs': 2, 'spam': 0} >>> d.update([('spam',1)]) >>> d {'bacon': 1, 'eggs': 2, 'spam': 1} ``` `update`函數將字典作為參數或鍵值對列表。 元組是這些鍵值對的理想候選者。 要從字典中刪除元素,可以使用眾所周知的`del`語句,并提供鍵和字典名稱。 自然,如果字典中不存在該鍵,則將得到一個`KeyError`。 `pop`函數將刪除具有給定鍵的元素,并返回與此鍵關聯的值。 如果鍵不存在,您將收到`KeyError`。 要解決此問題,您可以將`pop`函數傳遞給默認值,當給定鍵不在字典中時會返回該默認值。 `popitem`函數從字典中刪除一個元素,然后將已刪除的(鍵,值)對作為元組返回。 在這里,您不知道返回哪個元素。 如果字典為空,則您將收到`KeyError`。 ```py >>> food_preferences = {'bacon': 'yes', 'sausage': 'no', 'eggs': 'yes', 'spam': 'no'} >>> del food_preferences['spam'] >>> food_preferences {'bacon': 'yes', 'sausage': 'no', 'eggs': 'yes'} >>> del food_preferences['spam'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'spam' >>> food_preferences.pop('spam') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'spam' >>> food_preferences.pop('eggs') 'yes' >>> food_preferences {'bacon': 'yes', 'sausage': 'no'} >>> food_preferences.pop('spam','no') 'no' >>> food_preferences.popitem() ('bacon', 'yes') >>> food_preferences {'sausage': 'no'} >>> food_preferences.clear() >>> food_preferences {} >>> food_preferences.popitem() Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'popitem(): dictionary is empty' ``` ## 字典中有特定的鍵嗎? 有時,您只是想避免使用`get`函數,因為如果請求的鍵不在字典中,則不需要任何默認值。 在這種情況下,可以在帶有字典鍵的語句中使用它們。 ```py >>> d = {'eggs': 1, 'sausage': 2, 'bacon': 1} >>> d {'bacon': 1, 'sausage': 2, 'eggs': 1} >>> 'spam' in d False >>> 'eggs' in d True >>> 'Eggs' in d False ``` 如您在上面的示例中看到的,按鍵是按鍵敏感的。 這意味著字典可以包含鍵“垃圾郵件”,“垃圾郵件”和“垃圾郵件”,并且它們全部將引用不同的條目。 ## 字典的鍵和值 有時,您僅需要信息字典中存在哪些鍵,或者您想知道其中存在哪些值,或者僅當鍵存在時才需要這些值。 在這種情況下,可以使用字典的鍵或值方法。 您可能會認為它們會給您帶回字典中類似鍵或值的集合的對象。 讓我們來看一個示例。 ```py >>> d = {'first_name': 'Gabor', 'age':31, 'twitter':'@GHajba'} >>> d {'first_name': 'Gabor', 'age': 31, 'twitter': '@GHajba'} >>> d.keys() dict_keys(['first_name', 'age', 'twitter']) >>> d.values() dict_values(['Gabor', 31, '@GHajba']) ``` 這些類似集合的對象不可索引,但是您可以稍后在循環中使用它們。 當您想查看字典中是否有值時,`dict_values`對象很有用。 ```py >>> d = {'first_name': 'Gabor', 'age':31, 'twitter':'@GHajba'} >>> "Gabor" in d.values() True >>> "twitter" in d.values() False ``` 自然地,您可以使用`list`函數并將這些類似于字典`set`的對象轉換為`list`(或者使用`set`關鍵字來設置`set`或使用`tuple`函數,您可以創建一個包含所有項目的元組-希望您能理解其中的內容) 。 ```py >>> list(d.keys()) ['first_name', 'age', 'twitter'] >>> tuple(d.values()) ('Gabor', 31, '@GHajba') >>> set(d.items()) {('first_name', 'Gabor'), ('age', 31), ('twitter', '@GHajba')} ``` 如您在上面的示例中使用字典的 items 函數所看到的那樣,您將獲得一個成對的列表,其中第一個元素是鍵,第二個元素是值。 ### 參考文獻 * [字典](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)
                  <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>

                              哎呀哎呀视频在线观看