2

I want to remove some keys from a Python dictionary. The keys are provided in a list; my code so far:

my_keys = [2,4]
my_dict = {1:"aaaa" , 2: "bbb", 3:"ccc", 4:"ddd" }

for number in my_keys:
    for key, value in my_dict.items():
            if key == number:
                del my_dict[(key)]
njzk2
  • 38,969
  • 7
  • 69
  • 107
krenkz
  • 484
  • 6
  • 15

3 Answers3

4

You can use a dict comprehension, like so:

{x:y for x,y in my_dict.items() if x not in my_keys}

As e0k and njzk2 have suggested in the comments, if you're happy to modify the existing dictionary, the following works better:

for key in my_keys:
    try:
        del my_dict[key]
    except KeyError:
        pass # Key wasn't in the dictionary at all.
ffledgling
  • 11,502
  • 8
  • 47
  • 69
2

Here's how you do it in place:

>>> my_keys = [2,4]
>>> my_dict = {1:"aaaa" , 2: "bbb", 3:"ccc", 4:"ddd" }
>>> for key in my_keys:
...     del my_dict[key]
... 
>>> my_dict
{1: 'aaaa', 3: 'ccc'}

As a sidenote: To delete a key and get the value, use dict.pop

>>> x = my_dict.pop(1)
>>> x
'aaaa'
>>> my_dict
{3: 'ccc'}
timgeb
  • 76,762
  • 20
  • 123
  • 145
2

You could use a range with a step of 2, and then delete each key for each value in the range. You can also use map, which is a great function.

map(my_dict.pop, [2,4])

And if you want to catch an error where the key isn't in the dictionary, use a lambda function thus:

map(lambda x: my_dict.pop(x, None), [2,4])
Tom Fuller
  • 5,291
  • 7
  • 33
  • 42
opeonikute
  • 494
  • 1
  • 4
  • 15