【发布时间】: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