您的位置:首页 > 编程语言 > Python开发

Python dict del

2016-04-13 22:43 856 查看


Best
way to remove an item from a Python dictionary?






up
vote56down
votefavorite
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?

python
shareimprove
this question
asked Mar 27 '11 at 5:47





Buttons840
2,40952549

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. – ShadowGiraffe Jul
26 '15 at 19:21
add
a comment


9 Answers

activeoldestvotes

up vote52down
voteaccepted
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
.

shareimprove
this answer
edited Mar
27 '11 at 6:15

answered Mar 27 '11 at 5:51




Tim Pietzcker
185k22235331

2
Is that a dictionary compression? When were they added? – Buttons840 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 – J.F.
Sebastian Mar
27 '11 at 5:57
3
I believe dictionary comprehensions were added in Python 2.7. – mithrandi 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. – Tim
Pietzcker Mar
27 '11 at 6:00
@Buttons840 they are called dict
comprehensions in PEP 274 or dictionary displays.
as the PEP says they were added in 2.7 as backported 3.x feats.
alternatively you can feed
dict()
with
an appropriate generator expression, which is 2.4. meta: can browse the peps here for finding
stuff out. – n611x007 May
29 '14 at 11:43
add
a comment





up vote64down
vote
>>> dic = {'a':1, 'b':2}
>>> dic
{'a': 1, 'b': 2}
>>> dic.pop('c', 0)
0
>>> dic.pop('a', 0)
1
>>> dic
{'b': 2}


shareimprove
this answer
answered Mar 27 '11 at 5:55




N 1.1
9,11322847

add
a comment
up vote28down
vote
a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']


shareimprove
this answer
edited Dec
17 '13 at 16:31

answered Mar 27 '11 at 8:18




kracekumar
4,82122539

add
a comment
up vote23down
vote
A simple comparison between del and pop():
import timeit
code = """
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.0329667857143
0.0451040902256


So, del is faster than pop().

shareimprove
this answer
answered Feb 7 '13 at 3:04





Luu Tuan Anh
30328

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
del
operator. – Alex
Dupuy 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. – Adam_G May
1 '15 at 1:02
add
a comment
up vote7down
vote
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 would be problematic, and likewise for
viewitems()
in
Python 2.7.

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

shareimprove
this answer
answered Mar 27 '11 at 5:52




mithrandi
1,060521

add
a comment
up vote5down
vote
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]


shareimprove
this answer
answered Mar 27 '11 at 9:34

user97370

add
a comment
up vote0down
vote
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://docs.python.org/library/stdtypes.html#typesmapping

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: