如何遍历python字典并替换子字符串值?

时间:2019-01-02 20:27:32

标签: python string python-2.7 dictionary replace

我想遍历带有未知键的字典并替换特定的子字符串值。

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, '')

我想要的结果是:

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

如何遍历字典并替换特定的子字符串值?

2 个答案:

答案 0 :(得分:3)

它无法正常工作,因为v是一个列表,而不是单个字符串。因此,v.contains(val)始终为False。完成您所描述的内容的一种方法是:

for k, v in mydict.iteritems():
  for i, s in enumerate(v):
    if val in s:
      v[i] = s.replace(val, '')

答案 1 :(得分:1)

假设您的字典值是包含字符串的所有列表,并且您想从包含它的任何字符串中删除该值,则可以尝试:

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