Home > OS >  removing a dictionary key if its value is null
removing a dictionary key if its value is null

Time:11-13

This applies to python and pandas. I have created many dictionaries from which I want to remove certain keys where its value is null.

I have tried using the following code:

for d in dicties:

    if d['number1'] is not None:

        d['number1'] = int(d['number1'])

for d in dicties:

    if d['number2'] is not None:

        d['number2'] = int(d['number2'])
    elif d['number2'] is None:
        del d['number2']

But I am getting the following error:

RuntimeError: dictionary changed size during iteration

I am aware that the following code could be in the right direction:

for number2, value in list(dicties.items()):
if (value == ''):
    del dicties[key]

But there I am getting the following error:

AttributeError: 'list' object has no attribute 'items'

Does anybody have a suggestion?

CodePudding user response:

It's generally easier to create a new dictionary (or list) via comprehension than to mutate the original, especially if you're iterating over the original in order to make the changes.

dicties = [{k: v for k, v in d.items() if v is not None} for d in dicties]

e.g.:

>>> dicties = [{"foo": None, "bar": 1}, {"foo": 2, "bar": None}]
>>> dicties = [{k: v for k, v in d.items() if v is not None} for d in dicties]
>>> dicties
[{'bar': 1}, {'foo': 2}]
>>> 

CodePudding user response:

Try to pop:

d.pop('number2', None)

in place of:

del d['number2']

CodePudding user response:

This should do the job

d = {k: v for k, v in d.items() if v is not None}
  • Related