0

I want to loop through a dictionary with unknown keys and replace a specific substring value.

mydict = {
    '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/'
    ]
}

val = "+-BROKEN-"

for k, v in mydict.iteritems():
   if v.contains(val):
     v.replace(val, '')

The result I want is:

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

How can I loop through a dictionary and replace a specific substring value?

2 Answers 2

3

It's not working like you expect because v is a list, not a single string. For that reason, v.contains(val) is always False. One way to accomplish what you're describing would be:

for k, v in mydict.iteritems():
  for i, s in enumerate(v):
    if val in s:
      v[i] = s.replace(val, '')
Sign up to request clarification or add additional context in comments.

2 Comments

This looks great. I'm getting an error, though, because I have an odd character in the string: ├─BROKEN─ error is: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128) I tried s = '├─BROKEN─' val = unicode(s, "utf-8") but same error. Any advice? I'm using 2.7
You might try s = u'├─BROKEN─' and see if that does anything for you. You might also try something like finding an example that contains the value you want to replace and assigning it based on a substring. Something like val = mydict.values()[0][0][:10] to get the first ten characters of the first entry in the first list in the dict, for example.
1

Assuming your dictionary values are all lists which contain strings and you want to remove the value from any string containing it, you could try:

for k, v in mydict.iteritems():
    mydict[k] = [string.replace(val,'')] for string in v]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.