use*_*024 4 dictionary replace python-3.x
我有一本字典,看起来像:
d = {'alleged': ['truths', 'fiels', 'fact', 'infidelity', 'incident'],
'greased': ['axle', 'wheel', 'wheels', 'fields', 'enGine', 'pizza'],
'plowed': ['fields', 'field', 'field', 'incident', '', '']}
Run Code Online (Sandbox Code Playgroud)
我想检查它并用另一个字符串替换一些项目。要查找的字符串和替换它们的字符串也在字典中,其中键是要查找的字符串,值是要替换的字符串:
d_find_and_replace = {'wheels':'wheel', 'Field': 'field', 'animals':'plants'}
Run Code Online (Sandbox Code Playgroud)
我尝试使用如下函数:
def replace_all(dic1, dic2):
for i, j in dic.items():
dic3 = dic1.replace(i, j)
return(dic3)
Run Code Online (Sandbox Code Playgroud)
但它不会工作,因为很明显,它在其中使用了替换内置函数replace,并且不可能将它用于字典。关于如何做到这一点的任何建议?非常感谢您的帮助。
编辑以纠正拼写错误。
尝试只使用直接分配:
for key in d:
li = d[key]
for i,item in enumerate(li):
li[i] = d_find_and_replace.get(item, item)
Run Code Online (Sandbox Code Playgroud)