I want to remove values from a dictionary if they contain a particular string and consequentially remove any keys that have an empty list as value.
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}
With simple loop:
val = "is"
new_dict = dict()
for k, v in mydict.items():
values = [i for i in v if val not in i]
if values: new_dict[k] = values
print(new_dict)
The output:
{'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/']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With