How to loop through a dictionary to remove values that match a string?

  • A+
Category:Languages

I want to remove values from a dictionary if they contain a particular string, and any keys that have no values as a result.

mydict = {'Getting links from: https://www.foo.com/': ['+---OK--- http://www.this.com/', '+---OK--- http://www.is.com/', '+-BROKEN- http://www.broken.com/', '+---OK--- http://www.set.com/', '+---OK--- http://www.one.com/'], 'Getting links from: https://www.bar.com/': ['+---OK--- http://www.this.com/', '+---OK--- http://www.is.com/', '+-BROKEN- http://www.broken.com/'], 'Getting links from: https://www.boo.com/': ['+---OK--- http://www.this.com/', '+---OK--- http://www.is.com/']}  val = "is"  for k, v in mydict.iteritems():    if v.contains(val):      del mydict[v] 

The result I want is:

{'Getting links from: https://www.foo.com/': ['+-BROKEN- http://www.broken.com/', '+---OK--- http://www.set.com/', '+---OK--- http://www.one.com/'], 'Getting links from: https://www.bar.com/': ['+-BROKEN- http://www.broken.com/']} 

How can I remove all dictionary values that contain a string, and then any keys that have no values as a result?

 


You can use a list comprehension within a dictionary comprehension. You shouldn't change the number of items in a dictionary while you iterate that dictionary.

res = {k: [x for x in v if 'is' not in x] for k, v in mydict.items()}  # {'Getting links from: https://www.foo.com/': ['+-BROKEN- http://www.broken.com/', #                                               '+---OK--- http://www.set.com/', #                                               '+---OK--- http://www.one.com/'], #  'Getting links from: https://www.bar.com/': ['+-BROKEN- http://www.broken.com/'], #  'Getting links from: https://www.boo.com/': []} 

If you wish to remove items with empty list values, you can in a subsequent step:

res = {k: v for k, v in res.items() if v} 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: