Delete dictionary item if its key contains word

4231 views python
0

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

answered question

1 Answer

0

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)

posted this

Have an answer?

JD

Please login first before posting an answer.