Reputation: 2569
In Python 3, how do I copy a dictionary leaving out just one element? Data sharing among the two dicts is fine for me. Currently I have this code in mind:
def copy_leaving_out(dictionary, key):
return {k: v for k, v in dictionary if k != key}
Is there a better way to achieve this?
EDIT: I forgot to use dictionary.items()
instead of dictionary
, please consider the following code instead of the previous one:
def copy_leaving_out(dictionary, key):
return {k: v for k, v in dictionary.items() if k != key}
Upvotes: 0
Views: 251
Reputation: 149776
Using a dictionary comprehension is fine (and pythonic). However, to iterate over the key/value pairs you need to call dictionary.items()
:
def copy_leaving_out(dictionary, key):
return {k: v for k, v in dictionary.items() if k != key}
If you want to be more explicit, you can also use dictionary.copy()
to create a shallow copy of the dictionary, then remove the needed key:
def copy_leaving_out(dictionary, key):
copy = dictionary.copy()
del copy[key]
return copy
Performance-wise, the second version appears to be noticeably faster, probably because it doesn't involve key comparisons:
In [14]: d = {k: k for k in range(200)}
In [15]: %timeit copy_leaving_out_dc(d, 100)
13.9 µs ± 724 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [16]: %timeit copy_leaving_out_copy(d, 100)
738 ns ± 4.45 ns per loop (mean ± std. dev. of 7 runs, 1000000 loopseach)
Upvotes: 5
Reputation: 3620
I don't think you need to use a dictionary comprehension. It would suffice just to drop this key.
d = {1: 10, 2:20, 3:30}
res = d.copy()
res.pop(1)
10
res
{2: 20, 3: 30}
Upvotes: 1
Reputation: 7585
Use items()
functions in dictionary comprehensions
to get key and value and finally using if
clause -
d={'a':1,'b':2,'c':3}
key_remove = 'a'
d_out = {k:v for k,v in d.items() if k != key_remove }
print(d_out)
{'b': 2, 'c': 3}
Upvotes: 1