Delete dictionary item if its key contains word

Viewed 3014

I have this dictionary:

a={'sting1':1,'string2':2,'string3':3,'string4 null':4}

I want to delete items where key contains word null.

output={'sting1':1,'string2':2,'string3':3}

I found startswith application, and tried to work with key.find('null')!=-1 , but that didn't work out

3 Answers

Do dictionary comprehension:

print({k:v for k,v in a.items() if not 'null' in k})

If version below 2.6:

print(dict((k,v) for k,v in a.iteritems() if not 'null' in k))

See iteritems, not items, that's in python 2 only (all of python 2 versions)

"You can also write if 'null' not in k which some people find easier to read", thanks to @john.

In Python, to check if a string is contained in another string you can simply use the in keyword like this:

if "null" in "something null bla bla":
    # null is in the string

To delete all the items that contain null you can therefore simply loop over them, check if they contain null and remove them if they do:

for key in list(a.keys()):
    if "null" in key:
        del a[key]

Note that we have to create a list of all the keys, otherwise we can't remove items from the dict while iterating.

If you want to create a new dict with the items removed you can use a dict comprehension as the other answer shows or just use a plain old for loop:

output = {}
for key, value in a.items():
    if "null" not in key:
        # key is ok => add to output
        output[key] = value

This can also be done in-place:

l = []
for k in a:
    if 'null' in k:
        l.append(k)

for k in l:
    del a[k]

Or not:

b = {}
for k in a:
    if 'null' not in k:
       b[k] = a[k]
Related