-1

I have some dictionaries in two different text files. I have to open the text files and read them and then merge the three dictionaries. Somehow I cannot use update to merge these three dictionaries. The merging should be such where similar keys are added for example CCG in car1 and car2 should be summed.

So basically the data in text files are as follows:

TEXTFILE1

car1=[DictX= [{'ID':'AAT','Num': 7, 'ID':'CCG','Num': 45}]

car2=[DictZ= [{'ID':'CCG','Num': 10, 'ID':'TTT','Num': 8, 'ID':'ATU','Num': 14}]

TEXTFILE2 car3=[DictD= [{'ID':'GHA','Num': 85, 'ID':'TTT','Num': 2, 'ID':'ATU','Num': 0}]

diya09
  • 1
  • 1

2 Answers2

0

Say you have two files dict1.txt and dict2.txt containing dictionaries that need to be combined.

# dict1.txt
{"test1":123, "test2":456}
# dict2.txt
{"test3":789, "test4":101112}

Then to load and combine them the following function can be used:

import json

def load_dictionaries(file_names):
    master_dictionary = {}
    for file_name in file_names:
        with open(file_name, 'r') as f:
            for line in f:
                dictionary = json.loads(line.strip())
                master_dictionary.update(**dictionary)
    return master_dictionary

Which returns {'test1': 123, 'test2': 456, 'test3': 789, 'test4': 101112}

To answer the question regarding the update function, it takes a dictionary or a combination of key/value pairs. I am assuming you are getting undesired behavior because of the way you are loading your dictionaries, not the use of the update function itself.

ChrisOram
  • 1,254
  • 1
  • 5
  • 17
0

Assuming you have read the file into a variable like:

with open('x.txt') as x: f = x.read()

And done any processing to create the dictionary; Merging dictionaries is simple check this link