博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python dict del
阅读量:4031 次
发布时间:2019-05-24

本文共 4173 字,大约阅读时间需要 13 分钟。

56
13

What is the best way to remove an item from a dictionary? Here's a simple approach:

for key, item in some_dict.items():    if item is item_to_remove:        del some_dict[key]

Are there better ways? Is there anything wrong with mutating (deleting items) from the dictionary while iterating it?

 
 
The underline reason for prohibiting mutating dict while iterating it is because internally there is an order for iteration, if you mutate the keys, the order would be undermined, which results unknown behavior. –   
Jul 26 '15 at 19:21 

9 Answers

52
accepted

Be aware that you're currently testing for object identity (is only returns True if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==). If you are doing this on purpose, then you could rewrite your code as

some_dict = {key: value for key, value in some_dict.items()              if value is not value_to_remove}

But this may not do what you want:

>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}>>> value_to_remove = "You say yes">>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}>>> some_dict{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}>>> some_dict{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}

So you probably want != instead of is not.

 
2  
Is that a dictionary compression? When were they added? –   
Mar 27 '11 at 5:52
3  
you could use some_dict.iteritems() here and put for and if statements on separate lines for readability –   
Mar 27 '11 at 5:57
3  
I believe dictionary comprehensions were added in Python 2.7. –   
Mar 27 '11 at 5:58
2  
@J.F. Sebastian: I'm on Python 3, and iteritems is now items. In Python 2.7, iteritems() is indeed better. –   
Mar 27 '11 at 6:00
 
@Buttons840 they are called  or . as the PEP says they were  as backported 3.x feats. alternatively you can feed dict() with an appropriate generator expression, which is 2.4. meta: can  for finding stuff out. –   
May 29 '14 at 11:43
64
>>> dic = {'a':1, 'b':2}>>> dic{'a': 1, 'b': 2}>>> dic.pop('c', 0)0>>> dic.pop('a', 0)1>>> dic{'b': 2}
 
28
a = {'name': 'your_name','class': 4}if 'name' in a: del a['name']
 
23

A simple comparison between del and pop():

import timeitcode = """results = {'A': 1, 'B': 2, 'C': 3}del results['A']del results['B']"""print timeit.timeit(code, number=100000)code = """results = {'A': 1, 'B': 2, 'C': 3}results.pop('A')results.pop('B')"""print timeit.timeit(code, number=100000)

result: 

0.03296678571430.0451040902256

So, del is faster than pop()

 
5  
However, the performance difference is not great, and if you want to avoid raising an exception, you can provide a second argument to pop() (as @n-1-1 does above) - which is not an option for the deloperator. –   
Jul 11 '14 at 7:46
 
Ancillary to the question, but I'd also been struggling to understand timeit. Thank you for this clear example. –   
May 1 '15 at 1:02
7

items() returns a list, and it is that list you are iterating, so mutating the dict in the loop doesn't matter here. If you were using iteritems() instead, mutating the dict in the loop , and likewise for viewitems() in Python 2.7.

I can't think of a better way to remove items from a dict by value.

 
5

I'd build a list of keys that need removing, then remove them. It's simple, efficient and avoids any problem about simultaneously iterating over and mutating the dict.

keys_to_remove = [key for key, value in some_dict.iteritems()                  if value == value_to_remove]for key in keys_to_remove:    del some_dict[key]
 
0

There is nothing wrong with deleting items from the dictionary while iterating, as you've proposed. Be careful about multiple threads using the same dictionary at the same time, which may result in a KeyError or other problems.

Of course, see the docs at 

转载地址:http://xohbi.baihongyu.com/

你可能感兴趣的文章
绘图和可视化(pandas)
查看>>
绘图和可视化(seaborn)
查看>>
Vim日常使用
查看>>
计算机网络第一记:网络核心
查看>>
信息检索:基于知识图谱和深度学习的文本表示和搜索(Explicit and distributed semantics for text representation and retrieval)
查看>>
计算机网络第二记:协议层次
查看>>
计算机网络第三记:网络安全
查看>>
深度学习训练中如何处理NaNs
查看>>
机器学习与其他相似概念
查看>>
深度学习库提供了什么?
查看>>
Theano中如何只更新一部分权重,用法及理由。
查看>>
深度学习实践
查看>>
机器学习探索性数据分析的数据类型
查看>>
机器学习探索性数据分析的数据类型(补充)
查看>>
机器学习中典型工作流程
查看>>
数据挖掘十大算法 and 算法概述
查看>>
机器学习中样本数据预处理
查看>>
机器学习中样本缺失值的处理方法
查看>>
机器学习中样本比例不平衡的处理方法
查看>>
机器学习中的文本处理
查看>>