missingfaktor
missingfaktor

Reputation: 92046

Removing one or multiple keys from a dictionary

In Scala, to remove one key from a dictionary I need to do (pasted from REPL):

scala> Map(9 -> 11, 7 -> 6, 89 -> 43) - 9
res4: scala.collection.immutable.Map[Int,Int] = Map(7 -> 6, 89 -> 43)

To remove multiple keys:

scala> Map(9 -> 11, 7 -> 6, 89 -> 43) -- Seq(9, 89)
res5: scala.collection.immutable.Map[Int,Int] = Map(7 -> 6)

What is the Python way of doing this? (I posted Scala examples because that's the background I come from.)

Upvotes: 0

Views: 6854

Answers (2)

shantanoo
shantanoo

Reputation: 3704

>>> d = {"a": 1, "b": 2, "c": 3}
>>> for _ in ['a','c']: del(d[_])
... 
>>> d
{'b': 2}

Upvotes: 1

David Robinson
David Robinson

Reputation: 78600

If d is your dictionary and k the key you want to remove:

d.pop(k)

For example:

d = {"a": 1, "b": 2, "c": 3}
d.pop("a")
print d
# {'c': 3, 'b': 2}

If you want to remove multiple:

for k in lst:
    d.pop(k)

If you want to do this non-destructively, and get a new dictionary that is a subset, your best bet is:

s = set(lst)
new_dict = {k: v for k, v in d.items() if k not in s}

You could use k not in lst instead of dealing with set(lst), but using set will be faster if the list of items to remove is long.

Upvotes: 7

Related Questions