【问题标题】:Find and replace strings in a python dictionary在 python 字典中查找和替换字符串
【发布时间】:2013-11-13 18:21:21
【问题描述】:

我有一本看起来像这样的字典:

d = {'alleged': ['truths', 'fiels', 'fact', 'infidelity', 'incident'],
 'greased': ['axle', 'wheel', 'wheels', 'fields', 'enGine', 'pizza'],
 'plowed': ['fields', 'field', 'field', 'incident', '', '']}

我想检查一下并用其他字符串替换一些项目。要查找的字符串和要替换的字符串也在字典中,其中键是要查找的字符串,值是要替换的字符串:

d_find_and_replace = {'wheels':'wheel', 'Field': 'field', 'animals':'plants'}

我尝试使用如下函数:

def replace_all(dic1, dic2):
    for i, j in dic.items():
        dic3 = dic1.replace(i, j)
    return(dic3)

但它不会起作用,因为很明显,它在其中使用了替换内置函数replace,并且不能将其用于字典。关于如何做到这一点的任何建议?非常感谢您的帮助。

已编辑以纠正拼写错误。

【问题讨论】:

  • 你的d_find_and_replace 字典有点乱。检查您的报价是否在正确的位置。
  • 您的 d 字典也有几个错误(alleged 上没有开头引号,greased 列表内的右括号)。清理它们,使其首先工作,然后您可以调试替换。

标签: python-3.x dictionary replace


【解决方案1】:

尝试只使用直接赋值:

for key in d:
    li = d[key]
    for i,item in enumerate(li):
        li[i] = d_find_and_replace.get(item, item)

【讨论】:

  • 非常感谢。这仅超过字典的一行。也许它需要合并列表理解?
  • @user2962024 呃。我不跟。这会遍历d 中的每个key,并对该键的每个列表项执行find_and_replace 操作。你想构建一个新的dict,而不是就地改变d
  • 再次感谢您的宝贵时间。对不起,我搞砸了一些事情,但现在我想通了。非常好的解决方案!我真的很感谢你!
【解决方案2】:

这里有一个解决方案。我还修复了你的字典,它们很乱。检查您的拼写,因为对于那些给定的键,我认为只有一个匹配项将被替换。例如engine永远不会匹配enGine,除非你不关心匹配大小写,在这种情况下你可以使用if val.lowercase()

d = {'alleged': ['truths', 'fiels', 'fact', 'infidelity', 'incident'],
     'greased': ['axle', 'wheel', 'wheels', 'fields', 'enGine', 'pizza'],
     'plowed': ['fields', 'field', 'field', 'incident', '', '']}

d_find_and_replace = {'fields': 'field', 'engine': 'engine', 'incidint':'incident'}

keys_replace = d_find_and_replace.keys()
print d
for key in d.keys():
    for i, val in enumerate(d[key], 0):
        if val in keys_replace:
            index_to_replace = keys_replace.index(val)
            d[key][i] = d_find_and_replace[keys_replace[index_to_replace]]

print d

【讨论】:

  • 感谢您的解决方案,但我认为这是 python 2,不是吗?我得到错误:AttributeError:'dict_keys'对象没有属性'index',你知道python 3.2的等价物是什么吗?再次感谢!
  • 我在发布的代码中没有使用任何dict_keys。你能用给你错误的代码编辑你的答案吗?
  • 我更新了我的答案,我认为问题在于我使用 index 作为 for 循环中的局部变量和 index 作为函数。我用i 替换了index 变量。让我知道它是否有效。
  • 对不起,没有区别,仍然收到消息:AttributeError: 'dict_keys' object has no attribute 'index' referring to index_to_replace = keys_replace.index(val)`。
  • 奇怪,print keys_replace 应该是一个列表['engine', 'fields', 'incidint']
猜你喜欢
  • 2021-09-05
  • 2020-01-03
  • 2011-08-22
  • 2015-09-22
  • 2019-06-24
  • 2016-01-13
  • 2011-10-23
  • 1970-01-01
相关资源
最近更新 更多