将Python字典的值写回文件

将Python字典的值写回文件,python,dictionary,replace,Python,Dictionary,Replace,我将两个XML文件中的信息提取到两个字典中,因为我想比较这些文件并更改其中一个文件中的信息 这些是我的字典: 源词典: d_source={'123': 'description_1', '456': 'description_2'} 目标字典: d_target={'123': '\n', '456': 'description_2'} 这是我的替换代码: for i in d_source: for j in d_target: if d_target[j]=='

我将两个XML文件中的信息提取到两个字典中,因为我想比较这些文件并更改其中一个文件中的信息

这些是我的字典:

源词典:

d_source={'123': 'description_1', '456': 'description_2'}
目标字典:

d_target={'123': '\n', '456': 'description_2'}
这是我的替换代码:

for i in d_source:
    for j in d_target:
        if d_target[j]=='\n':
            d_target[j]=d_source[i]
print (d_target)
d_目标更新为

d_target = {'123': 'description_1', '456': 'description_2'}

但是,从中提取词典的原始文件保持不变。我在这里遗漏了什么?

解决方案之一是:

假设您想将其打印为json,如果您已经在使用dicts,那么这是有意义的

import json 
output = json.dumps(d_target)

f = open("myfile", 'w')
f.write(output)
f.close()
这将以json格式将dict打印到文件myfile

如果您想将其作为xml,可以使用elementtree模块

然后你可以用这样的东西:

from elementtree import ElementTree as ETree
ET = ETree
ET.xml_declaration = "true"
products = ET.Element("products")
properties = ET.Element("properties")
products.append(properties)
products.attrib["xmlns"] = "http://schema.example.com/product_data_1.0"
update = ET.Element("update")
delete = ET.Element("delete")
products.append(delete)
products.append(update)
这只是一个例子,看看它是如何完成的,这将创建如下内容:

 <products xmlns="http://schema.example.com/product_data_1.0">
      <properties />
      <delete />
      <update />
 </products>
您的替换代码(在您的示例中)可以由
dict
上的
.update()
方法替换

d_target.update(d_source)

我不确定您希望如何持久化
dict
,但使用
json
模块是一种选择。否则,如果您想要更新的XML文件,您必须查看修改节点中的属性,并编写“somelibraryhere”.tostring()的(或类似)方法的结果。

如果您修改字典,您希望Python代码如何修改文件?我不知道,这就是为什么我要问的……我是Python新手。我想我可以将字典重新导入到我的文件中,但不知道如何导入。你需要将字典写回文件,字典和文件之间没有链接。请发布你的文件io代码。显示整个代码通常没有帮助。您应该粘贴足够的代码,以允许其他人重现您观察到的问题。你应该把它贴在这里,其他人不需要访问外部站点。(如果出现滚动条,可能代码太多。)JSON很简单。XML通常有点难,因为没有一对一的映射。但总的来说,这种方法是正确的。反序列化,更改,然后序列化。好主意!但不幸的是,我需要一个XML输出,否则我无法将文件重新导入到我的软件中:/。
d_target.update(d_source)