💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 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] ```