master
/ 7.2.3 修改字典值.ipynb

7.2.3 修改字典值.ipynb @master

d487d71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 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
 46
 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
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 修改字典值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "字典是一种可变的数据类型,支持数据元素的增加、删除和修改操作。仍以通讯录为例,在使用的过程中,可能需要向数据里插入新的联系人数据、更新原有的联系人的姓名或电话、删除其中的数据。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 元素值的修改与新增"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "+ ### 使用dict\\[key\\] = value方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**当键名key在字典中存在时将修改字典dict中键key的值为新值value**\n",
    "\n",
    "**当键名key在字典中不存在时将为字典增加以key为键以value为值的新元素**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'李明': '13988887788', '张宏': '13866668888', '赵雪': '13000112222'}\n"
     ]
    }
   ],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "# 键存在时更新\n",
    "tel_book['李明'] = '13988887788'  # 李明的电话更新为 '13988887788'\n",
    "tel_book['赵雪'] = '13000112222'  #新增元素 '赵雪': '13000112222'\n",
    "print(tel_book)                   # {'李明': '13988887788', '张宏': '13866668888', '赵雪': '13000112222'}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/1.png\" style=\"zoom:50%;\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "+ ### 使用dict.update(k1=v1[, k2=v2,…])方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**可以用dict.update(k1=v1[, k2=v2,…])方法同时更新字典中的多个值**\n",
    "\n",
    "**当字典dict中存在k1k2将对应的值修改为v1v2…;**\n",
    "\n",
    "**当不存在相应的键值时会将对应的k1:v1k2:v2键值对加入字典**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'李明': '13988887777', '张宏': '13866668877', '王晶': '13244441111'}\n"
     ]
    }
   ],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "# 将张宏的电话更新为'13866668877' ;'王晶'不存在以键值对形式加入到字典中\n",
    "tel_book.update(张宏='13866668877', 王晶='13244441111')  \n",
    "print(tel_book)  # {'李明': '13988887777', '张宏': '13866668877', '王晶': '13244441111'}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/2.png\" style=\"zoom:50%;\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "+ ### 使用dict.update(\\[other\\])方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**接受另一个字典对象或者一个包含键/值对以长度为二的元组或其他可迭代对象表示的可迭代对象**\n",
    "\n",
    "**当other中的键在字典dict中存在时将修改为对应的值**\n",
    "\n",
    "**当other中的键在字典dict中不存在时将键值对加入字典dict**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'李明': '13988887788', '张宏': '13866668888', '程钱': '13111223214'}\n"
     ]
    }
   ],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "tel_book2 = {'李明': '13988887788', '程钱': '13111223214'}\n",
    "tel_book.update(tel_book2)\n",
    "print(tel_book)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/3.png\" style=\"zoom:50%;\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "tel_book2 = [('李明', '13988887788'), ('程钱', '13111223214')]\n",
    "tel_book.update(tel_book2)   # 也可使用包含键/值对以长度为二的元组或其他可迭代对象表示的可迭代对象\n",
    "print(tel_book)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/4.png\" style=\"zoom:50%;\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "+ ### 使用dict.setdefault(key[, value])方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**当字典dict 中存在键key时返回key对应的值**\n",
    "\n",
    "**键key不存在时在字典中增加 key: value 键值对值value缺省时默认设其值为None**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "tel_book.setdefault('刘飞','13344556655')  # 为字典新增元素 '刘飞': '13344556655'\n",
    "tel_book.setdefault(('程钱'))              # 值缺省时默认为None为字典新增元素'程钱': None\n",
    "print(tel_book)\n",
    "phone_number = tel_book.setdefault('李明') # 存在键'李明'返回其值'13988887777'\n",
    "print(phone_number)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/5.png\" style=\"zoom:50%;\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (993078169.py, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  File \u001b[0;32m\"/tmp/ipykernel_173/993078169.py\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m    + ### 使用运算符“|”和 “|=”\u001b[0m\n\u001b[0m                        ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "+ ### 使用运算符“|”和 “|=”"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Python 3.9 以后版本新增**\n",
    "\n",
    "**d | other:合并 d 和 other 中的键和值来创建一个新的字典,两者必须都是字典。当 d 和 other 有相同键时, other 的值优先。**\n",
    "\n",
    "**d |= other:用 other 的键和值更新字典 d ,other 可以是字典或可迭代的键值对。当 d 和 other 有相同键时, other 的值优先。**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "tel_book2 = {'刘飞': '13344556655', '程钱': '13111223214'}\n",
    "tel = tel_book | tel_book2\n",
    "print(tel)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/6.png\" style=\"zoom:50%;\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "tel_book2 = {'刘飞': '13344556655', '程钱': '13111223214'}\n",
    "tel_book |= tel_book2 \n",
    "print(tel_book)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/7.png\" style=\"zoom:50%;\">\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典元素的删除\n",
    "\n",
    "+ ### 使用dict.pop(key[, default])方法\n",
    "\n",
    "**将键为 key 的键值对元素删除返回值为键 key 对应的值**\n",
    "\n",
    "**如果提供了default dict 中不存在 key 键时返回 default否则将会触发KeyValue异常**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "del_key = tel_book.pop('张宏')\n",
    "print('删除的联系人的电话是:', del_key)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/8.png\" style=\"zoom:50%;\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "del_key = tel_book.pop('李宏', '用户不存在')\n",
    "print('删除的联系人的电话是:', del_key)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/9.png\" style=\"zoom:50%;\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "del_key = tel_book.pop('李宏')       # 未设置default 将会触发KeyValue异常\n",
    "print('删除的联系人的电话是:', del_key)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "+ ### 使用dict.popitem()方法\n",
    "\n",
    "**从字典中移除并返回一个元组形式的(, ) **\n",
    "\n",
    "**键值对会按LIFOLast In, First Out, 后进先出顺序被返回即每次执行删除位于字典末尾的键值对**\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "delitem = tel_book.popitem() \n",
    "print('删除的联系人是:',delitem)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/10.png\" style=\"zoom:50%;\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果字典为空调用 popitem() 将引发 KeyError"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {}\n",
    "delitem = tel_book.popitem() \n",
    "print('删除的联系人是:',delitem)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "+ ### 使用dict.clear()方法\n",
    "\n",
    "**清空字典dict中所有数据保留空字典对象**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "tel_book.clear()  # 清空字典中的所有数据\n",
    "print(tel_book)   # {}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/11.png\" style=\"zoom:50%;\">\n",
    "\n",
    "+ ### 使用del dict[key]指令\n",
    "\n",
    "**将字典dict中键为key的键值对元素删除如果不存在键key则会引发 KeyError**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "del tel_book['张宏']   # 删除键为'张宏'的键值对\n",
    "print(tel_book)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/12.png\" style=\"zoom:50%;\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "del tel_book['李小明']   # '李小明'不存在引发KeyError\n",
    "print(tel_book)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "+ ### 使用del dict指令\n",
    "\n",
    "**将字典对象dict删除后续如果再次引用该对象将引发NameError**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "del tel_book     # 删除名为tel_book的字典对象\n",
    "print(tel_book)  # 触发NameError异常"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 视图可迭代数据\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用字典keys()values()和items()方法生成的可迭代数据是一种特殊的视图类数据这三个方法可以分别获得一个包含字典全部键值和键值对的对象  \n",
    "它们的值关联至原始字典<font color='red'>**当原始字典中的数据发生改变时其值也会发生变化**</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "ks = tel_book.keys()\n",
    "vs = tel_book.values()\n",
    "kvs = tel_book.items()\n",
    "print(ks)    # dict_keys(['李明', '张宏'])\n",
    "print(vs)    # dict_values(['13988887777', '13866668888'])\n",
    "print(kvs) #dict_items([('李明', '13988887777'), ('张宏', '13866668888')])\n",
    "tel_book.update(王晶='13244441111') #键王晶不存在将键值对加入字典\n",
    "print(tel_book)  #{'李明': '13988887777', '张宏': '13866668888', '王晶': '13244441111'}\n",
    "print(ks)   #print(ks)   dict_keys(['李明', '张宏', '王晶'])\n",
    "print(vs)  #dict_values(['13988887777', '13866668888', '13244441111'])\n",
    "print(kvs) #dict_items([('李明', '13988887777'), ('张宏', '13866668888'), ('王晶', '13244441111')])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/ch7/long/13.png\" style=\"zoom:50%;\">\n",
    "\n",
    "Python 3.7版之后:字典顺序会确保为插入顺序因此这三个方法的返回值也按插入顺序可以进行如下相关操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888'}\n",
    "ks = tel_book.keys()\n",
    "vs = tel_book.values()\n",
    "kvs = tel_book.items()\n",
    "print(len(kvs))          # 可使用len()函数获取元素个数\n",
    "print(list(zip(ks, vs))) # 允许使用zip()来创建 (, ) \n",
    "print([(k, v) for (k, v) in kvs])      # 允许使用推导式来创建 (, ) \n",
    "print(('李明', '13988887777') in kvs)  # 支持成员检测\n",
    "print(list(reversed(kvs)))  # 支持逆序返回一个逆序获取字典键值或项的迭代器"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "遍历字典时若字典元素被删除会导致字典长度发生变化而导致异常"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 删除字典中特定元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888', '李小明': '13988886666', '李广': '13988885555', }\n",
    "\n",
    "# 删除字典中姓的人的元素\n",
    "for user_name in tel_book:   # RuntimeError: dictionary changed size during iteration\n",
    "    if user_name[0] == '李':\n",
    "        tel_book.pop(user_name)\n",
    "print(tel_book)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "因字典的视图会随字典元素变化而发生变化所以也不可以通过遍历字典视图的方法删除字典中的元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888', '李小明': '13988886666', '李广': '13988885555', }\n",
    "\n",
    "# 删除字典中姓的人的元素\n",
    "for user_name in tel_book.keys():   # RuntimeError: dictionary changed size during iteration\n",
    "    if user_name[0] == '李':\n",
    "        tel_book.pop(user_name)\n",
    "print(tel_book)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为避免这个问题推荐两个方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 将字典的视图转为列表再用于控制遍历"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888', '李小明': '13988886666', '李广': '13988885555', }\n",
    "\n",
    "# 删除字典中姓的人的元素\n",
    "for user_name in list(tel_book.keys()):   # RuntimeError: dictionary changed size during iteration\n",
    "    if user_name[0] == '李':\n",
    "        tel_book.pop(user_name)\n",
    "print(tel_book)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 通过字典推导式的方法创建新的字典:\n",
    "新字典元素是删除是过滤掉特定元素后的结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888', '李小明': '13988886666', '李广': '13988885555', }\n",
    "# 删除字典中姓的人的元素\n",
    "tel_book_new = {x[0]: x[1] for x in tel_book.items() if x[0][0] != '李'}\n",
    "print(tel_book_new)  # {'张宏': '13866668888'}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 建议遍历时直接用两个变量可避免索引的使用使程序更容易理解"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tel_book = {'李明': '13988887777', '张宏': '13866668888', '李小明': '13988886666', '李广': '13988885555', }\n",
    "# 删除字典中姓的人的元素\n",
    "tel_book_new = {k: v for k, v in tel_book.items() if k[0] != '李'}\n",
    "print(tel_book_new)  # {'张宏': '13866668888'}"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}