33.md 8.9 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4
# Python 字典

> 原文: [https://www.programiz.com/python-programming/dictionary](https://www.programiz.com/python-programming/dictionary)

W
wizardforcel 已提交
5
#### 在本教程中,您将学习有关 Python 字典的所有知识; 如何创建,访问,添加,删除元素以及各种内置方法。
W
wizardforcel 已提交
6

W
wizardforcel 已提交
7
Python 字典是无序的项目集合。 字典的每个项目都有一个键值对。
W
wizardforcel 已提交
8 9 10 11 12 13 14 15 16

字典被优化以在键已知时检索值。

* * *

## 创建 Python 字典

创建字典就像将项目放在用逗号分隔的大括号`{}`中一样简单。

W
wizardforcel 已提交
17
项具有`key`和表示为一对的相应`value`**键值**)。
W
wizardforcel 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

虽然值可以是任何数据类型并且可以重复,但是键必须是不可变类型([字符串](/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()`方法中使用键。

W
wizardforcel 已提交
46
如果我们使用方括号`[]`,则在字典中找不到键的情况下会抛出`KeyError`。 另一方面,如果找不到密钥,则`get()`方法返回`None`
W
wizardforcel 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

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

* * *

## 更改和添加字典元素

字典是可变的。 我们可以使用赋值运算符添加新项或更改现有项的值。

W
wizardforcel 已提交
84
如果密钥已经存在,那么现有值将被更新。 如果键不存在,则将新的**键值**对添加到字典中。
W
wizardforcel 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

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

W
wizardforcel 已提交
103
**输出**
W
wizardforcel 已提交
104 105 106 107 108 109 110 111 112 113

```py
{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}
```

* * *

## 从字典中删除元素

W
wizardforcel 已提交
114
我们可以使用`pop()`方法删除字典中的特定项目。 此方法删除提供了`key`的项目并返回`value`
W
wizardforcel 已提交
115 116 117

`popitem()`方法可用于从字典中删除并返回任意的`(key, value)`项目对。 使用`clear()`方法可以一次删除所有项目。

W
wizardforcel 已提交
118
我们还可以使用`del`关键字删除单个项目或整个字典本身。
W
wizardforcel 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152

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

W
wizardforcel 已提交
153
**输出**
W
wizardforcel 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

```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 字典方法

W
wizardforcel 已提交
171
下表列出了字典可用的方法。 在上面的示例中已经使用了其中一些。
W
wizardforcel 已提交
172 173

| 方法 | 描述 |
W
wizardforcel 已提交
174
| --- | --- |
W
wizardforcel 已提交
175 176 177 178 179 180 181
| [`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`。 |
W
wizardforcel 已提交
182
| [`popitem()`](/python-programming/methods/dictionary/popitem) | 删除并返回任意项(**键值**)。 如果字典为空,则抛出`KeyError`。 |
W
wizardforcel 已提交
183 184 185
| [`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) | 返回字典值的新对象 |
W
wizardforcel 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

以下是这些方法的一些示例用例。

```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())))
```

W
wizardforcel 已提交
203
**输出**
W
wizardforcel 已提交
204 205 206 207 208 209 210 211 212 213 214

```py
{'Math': 0, 'English': 0, 'Science': 0}
('Math', 0)
('English', 0)
('Science', 0)
['English', 'Math', 'Science']
```

* * *

W
wizardforcel 已提交
215
## Python 字典推导式
W
wizardforcel 已提交
216

W
wizardforcel 已提交
217
字典推导式是一种用 Python 中的可迭代对象创建新字典的简洁明了方法。
W
wizardforcel 已提交
218

W
wizardforcel 已提交
219
字典推导式由一个表达式对(**键值**)和大括号`{}`中的`for`语句组成。
W
wizardforcel 已提交
220 221 222 223 224 225 226 227 228 229

这是制作字典的示例,其中每个项目都是一对数字及其平方。

```py
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}

print(squares)
```

W
wizardforcel 已提交
230
**输出**
W
wizardforcel 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243 244

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

W
wizardforcel 已提交
245
**输出**
W
wizardforcel 已提交
246 247 248 249 250

```py
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
```

W
wizardforcel 已提交
251
对于或[语句,字典推导式可以可选地包含更多](/python-programming/if-elif-else)[](/python-programming/for-loop)
W
wizardforcel 已提交
252 253 254 255 256 257 258 259 260 261 262 263

可选的`if`语句可以过滤出项以形成新字典。

以下是一些仅包含奇数项的字典的示例。

```py
# Dictionary Comprehension with if conditional
odd_squares = {x: x*x for x in range(11) if x % 2 == 1}

print(odd_squares)
```

W
wizardforcel 已提交
264
**输出**
W
wizardforcel 已提交
265 266 267 268 269

```py
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
```

W
wizardforcel 已提交
270
要了解更多字典推导式,请访问 [Python 字典推导式](/python-programming/dictionary-comprehension)
W
wizardforcel 已提交
271 272 273

* * *

W
wizardforcel 已提交
274
## 其他字典操作
W
wizardforcel 已提交
275 276 277

### 字典成员资格测试

W
wizardforcel 已提交
278
我们可以使用关键字`in`来测试`key`是否在字典中。 请注意,成员资格测试仅适用于`keys`,而不适用于`values`
W
wizardforcel 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

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

W
wizardforcel 已提交
295
**输出**
W
wizardforcel 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

```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])
```

W
wizardforcel 已提交
314
**输出**
W
wizardforcel 已提交
315 316 317 318 319 320 321 322 323 324 325

```py
1
9
25
49
81
```

* * *

W
wizardforcel 已提交
326
### 字典内置函数
W
wizardforcel 已提交
327

W
wizardforcel 已提交
328
诸如`all()``any()``len()``cmp()``sorted()`等内置函数通常与字典一起使用以执行不同的任务。
W
wizardforcel 已提交
329

W
wizardforcel 已提交
330 331
| 函数 | 描述 |
| --- | --- |
W
wizardforcel 已提交
332 333 334 335 336
| [`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) | 返回字典中新排序的键列表。 |
W
wizardforcel 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356

以下是一些使用内置函数来处理字典的示例。

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

W
wizardforcel 已提交
357
**输出**
W
wizardforcel 已提交
358 359 360 361 362 363 364

```py
False
True
6
[0, 1, 3, 5, 7, 9]
```