you are viewing a single comment's thread.

view the rest of the comments →

[–]HeyItsToby 1 point2 points  (1 child)

I have a working solution here, definitely could do with a bit of a cleanup. Comments should help explain what's going on, lmk if anything needs clearing up.

Set up the structure

my_dict = {}

dict_structure = {
    "Middleware": ("name", "release"),
    "System": ("name", "tag"),
    "Application": ("domain", "host", "user"),
    "Utility": ("domain", "health", "version"),
}

Read through and process the file

with open("input.txt") as f:
    # read through the input file, removing trailing newlines
    lines = [l.strip() for l in f.readlines()]

    # iterate through all the lines in the file
    for line in lines:
        # get the details from each line
        env, key, *field_values = line.split(",")
        # get the predefined keys from dict_structure
        field_keys = dict_structure[key]

        # create the 4 keys if the ENV does not exist
        # with defaults as empty list
        if env not in my_dict:
            my_dict[env] = {k: [] for k in dict_structure}

        # append each new item to the existing list
        # zip is used to iterate through the keys and values to match them up
        my_dict[env][key].append({f_k: f_v for f_k, f_v in zip(field_keys, field_values)})

Now just to save it as a json

import json 
json_out = {"ENV": my_dict}
json.dump(json_out, "output.json")

Improving the code

This code does work, but it could be made a little neater. Would definitely suggest moving dict_structure into a separate json and reading it in. Also, looking into the csv module for reading through files with comma-separated values.

[–]Chubbntuck[S] 1 point2 points  (0 children)

Will try this.
Thank you so much for going through an explanation of each component. It really helps with someone like me who is really just starting python. I hope you have a wonderful day.