Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 907
lane Avatar asked Dec 14 '22 13:12

lane


2 Answers

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}
like image 169
jpp Avatar answered Dec 22 '22 16:12

jpp


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/']}
like image 30
RomanPerekhrest Avatar answered Dec 22 '22 15:12

RomanPerekhrest