Home > front end >  Retrieve values from array of dictionary
Retrieve values from array of dictionary

Time:05-04

I'm trying to process a json file like below and extract its data in the below output format for further processing.

json file

{
    "application_robotics-2.1.610.80350109": [
        "/home/machine_process/application_robotics/services/linear_service/4.106.50109987/robotics.yaml",
        "/home/machine_process/application_robotics/services/linear_service/4.106.50109987/application_robotics-4.106.50109987.zip"
    ],
    "web_robotics-3.116.50100987": [
        "/home/machine_process/application_robotics/services/web_robotics/3.116.50100987/robotics.yaml",
        "/home/machine_process/application_robotics/services/web_robotics/3.116.50100987/web_robotics-3.116.50100987.zip"
    ]
}

Expected output format

name = "application_robotics-2.1.610.80350109" # where name is a variable to be used in the other portion of the code.
yaml = "/home/machine_process/application_robotics/services/linear_service/4.106.50109987/robotics.yaml" # where yaml is a variable.
zip = "/home/machine_process/application_robotics/services/linear_service/4.106.50109987/application_robotics-4.106.50109987.zip"  # where zip is a variable.

same format applied for other entries.

Below is the snippet code I've come up with and I'm not exactly getting the logic. Any help will be really helpful here. Thanks.

with concurrent.futures.ProcessPoolExecutor() as executor:
    with open(file_path, "r") as input_json:
        json_data = json.load(input_json)
        for key, value in json_data.items():
            name = json_data[key]
            yaml = json_data[value]
            zip = json_data[value]
            file_location = os.path.dirname(tar)
            futures = executor.submit(
                other_function_name, yaml, zip, file_location, name
            )
            results.append(futures)

Current Output:

['home/machine_process/application_robotics/services/linear_service/4.106.50109987/robotics.yaml', '/home/machine_process/application_robotics/services/linear_service/4.106.50109987/application_robotics-4.106.50109987.zip']

CodePudding user response:

Since name corresponds to the keys; yaml to the first element of lists; and zip_ to the second elements (note that zip is a python builtin, so avoid using it as a variable name), we can directly unpack it as we loop over the dictionary and pass these to executor.

with concurrent.futures.ProcessPoolExecutor() as executor:
    with open(file_path, "r") as input_json:
        json_data = json.load(input_json)
        for name, (yaml, zip_) in json_data.items():
            file_location = os.path.dirname(tar)
            futures = executor.submit(other_function_name, yaml, zip_, file_location, name)
            results.append(futures)
  • Related