1

In the beginning I create xls_dict and xml_dict

Then wrapped the above 2 dicts into dictionary's creation. (I though it is copy be reference)

So I will load the json files into the 2 dicts.

However, I found when I exit the

for export_file, data_dict in json_files.iteritems(): block.

the xls_dict and xml_dict are not changed.

The was not my expectation.

Where did I misunderstand ? Thanks

    xls = MultiLangXls(xls_path, XLS_COLUMN)
    xls_dict = xls.load()
    xml = MultiLangXML(xml_path)
    xml_dict = xml.load()

    json_files={
        "xls.json": xls_dict,
        "xml.json": xml_dict
    }

    for export_file, data_dict in json_files.iteritems():
        if os.path.isfile(export_file):
            pass
        else: # If json file not exists, then ouput the dict into json file
            with open( export_file , 'w') as f:
                json.dump(data_dict, f, encoding="utf-8")
        load_file = open(export_file).read().decode("utf-8-sig")
        data_dict = {}
        data_dict = json.loads( load_file ) 
newBike
  • 14,385
  • 29
  • 109
  • 192

3 Answers3

2

The data_dict variable does refer to the same object and not to a copy. Assigning a new dict to data_dict, however, disconnects the variable from that object and assigns to it a brand new one.

To clear the existing dict, and fill it with new contents, you want to write something like this:

data_dict.clear()
data_dict.update(json.loads(load_file))
user4815162342
  • 141,790
  • 18
  • 296
  • 355
0

You are reassigning data_dict to a new dictionary object.

See Passing values in Python

Community
  • 1
  • 1
IceArdor
  • 1,961
  • 19
  • 20
0

Problem here:

data_dict = {} #You create new empty dictionary
# And rewrite it. But old dictionare are not cleaned.
data_dict = json.loads( load_file ) 

You must clean by data_dict.clean()

Michael Kazarian
  • 4,376
  • 1
  • 21
  • 25