Write values of Python dictionary back to file

2019-02-28 22:14发布

问题:

I extracted information from two XML files into 2 dictionaries because I wanted to compare these files and change information in one of them.

These are my dictionaries:

source dictionary:

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

target dictionary:

d_target={'123': '\n', '456': 'description_2'}

This is my replacement code:

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_target is updated to

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

However, my original files from which I extracted the dictionaries remain unchanged. What am I missing here?

回答1:

One of the solutions for you would be:

Let's say you want to print it as a json, it makes sense if you are already using dicts.

import json 
output = json.dumps(d_target)

f = open("myfile", 'w')
f.write(output)
f.close()

This will print your dict to file myfile as a json.

And if you want it as a xml you can use elementtree module.

Then you could use something like this:

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)

This is just an example to see how it is done and this would create something like:

 <products xmlns="http://schema.example.com/product_data_1.0">
      <properties />
      <delete />
      <update />
 </products>

And to print this xml to file again:

output = ET.tostring(products, "utf-8")
f = open("xml", 'w')
f.write(output)
f.close()


回答2:

Your replacement code (in your example) can be replaced by the .update() method on a dict.

d_target.update(d_source)

I'm not sure how you want to persist the dict but using the json module is one option. Otherwise if you wanted an updated XML file, you'll have to look at modifying attributes in the nodes, and writing the result of "somelibraryhere".tostring()'s (or similar) method.