1

I'm trying to iterate over a dictionary in order to delete all items where the key is a number.

dict= {'hello':'3', 'baby':'5', '33':'6'}

for k in dict.keys():
    if k.isdigit():
       del dict[k]

The result i need is this:

dict={'hello':'3', 'baby':'5'}

I use the code above but it doesn't work? Can somebody help me?

CosimoCD
  • 3,570
  • 3
  • 22
  • 31
  • 1
    That seems to work just fine when I run your code. On a side note, naming your variables after basic python types (like `dict`) is at some point going to cause you grief. – larsks Dec 16 '16 at 16:16

4 Answers4

3

Instead of deleting items while looping through the dictionary, you can create a new dictionary:

dict_ = {'hello':'3', 'baby':'5', '33':'6'}

{k: v for k, v in dict_.items() if not k.isdigit()}
# {'baby': '5', 'hello': '3'}
Psidom
  • 209,562
  • 33
  • 339
  • 356
1

The error RuntimeError: dictionary changed size during iteration, as it said, is raised because the dictionnary is modified during the iteration. One solution could be to first register all the keys, then modify the dictionnary:

dict= {'hello':'3', 'baby':'5', '33':'6'}

for k in tuple(dict.keys()):  # iterate on a tuple of values that happened to be in dict's keys
    if k.isdigit():
       del dict[k]

The other, more pythonic, is to build the dictionnary in place, for instance using the dictionnary in intension notation like in this answer.

Btw, dict is a very bad name for an object of type dict.

Community
  • 1
  • 1
aluriak
  • 5,559
  • 2
  • 26
  • 39
0

The problem is because you are updating the dictionary while traversing. Rather first store the keys in a list and then remove from the dictionary.

Try this:

dic= {'hello':'3', 'baby':'5', '33':'6'}

x=dic.keys()
for k in x:
    if k.isdigit():
       del dic[k]
print dic

output :

{'baby': '5', 'hello': '3'}
Karan Nagpal
  • 341
  • 2
  • 10
  • 1
    This still doesn't work for for me in python 3. `x = list(dic.keys()) or tuple(dic.keys())` is probably the way to go(didn't down vote though). – Psidom Dec 16 '16 at 16:27
  • this works in python 2. you didnt mention anywhere that you need it for python 3 specifically! – Karan Nagpal Dec 18 '16 at 16:20
0

Here is another solution using pop and map to modify in place your initial dictionary:

my_dict = {'a':1, 'b':2, 'c':3, '11':4, '12':5} 
_ = map(lambda k: my_dict.pop(k), [k for k in my_dict if k.isdigit()])
# The map functions modifies in place your dictionary

Output :

>> my_dict
>> {'a': 1, 'b': 2, 'c': 3}
MMF
  • 5,750
  • 3
  • 16
  • 20