# 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) ``` 要拥有带有值的字典,我们必须在这些花括号之间添加键-值对。 键具有与`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 "", line 1, in 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 "", line 1, in KeyError: 'spam' >>> food_preferences.pop('spam') Traceback (most recent call last): File "", line 1, in 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 "", line 1, in 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)