Home > Net >  Appending python dictionary values to a python list
Appending python dictionary values to a python list

Time:02-03

I am trying to process my api result string the result string format is given below. My goal is to add these values to a list where each element of list will be a dictionary.

result_str = '['{"abc.xyz": "80983098429842","dev.uvw": 898420920},' \
                 '{"abc.xyz": "80983098429843","dev.uvw": 898420921},' \
                 '{"abc.xyz": "80983098429844","dev.uvw": 898420922}]'

However my code is returning a list that has only last element multiple times. Rather than having each element once.

Here is my code:

import json

def format_api_value(result_str, split_char, label_map):
    results = json.loads(result_str)
    d = dict()
    output = []
    for item in results:
        output.append(d)
        print(f"clearing d after appending {d} \n")
        d.clear()
        for k, v in item.items():
            if split_char in k:
                key = k.split(split_char)[len(k.split(split_char))-1]
                if key in label_map:
                    key = label_map[key]

                d[key] = v
            else:
                d[k] = v
        print(f"printing output intermediate {output}")
    print(f"returning final list output")
    print(output)
    return d


if __name__ == "__main__":
    result_str = '[' \
                 '{"abc.xyz": "80983098429842","dev.uvw": 898420920},' \
                 '{"abc.xyz": "80983098429843","dev.uvw": 898420921},' \
                 '{"abc.xyz": "80983098429844","dev.uvw": 898420922}]'
    split_char = "."
    label_map = {"xyz": "xyz_1", "uvw": "uvw_1"}

    format_api_value(result_str, split_char, label_map)

Expected Output:

[{'xyz_1': '80983098429842', 'uvw_1': 898420920}, {'xyz_1': '80983098429843', 'uvw_1': 898420921}, {'xyz_1': '80983098429844', 'uvw_1': 898420922}]

Current Output:

[{'xyz_1': '80983098429844', 'uvw_1': 898420922}, {'xyz_1': '80983098429844', 'uvw_1': 898420922}, {'xyz_1': '80983098429844', 'uvw_1': 898420922}]

CodePudding user response:

All you need is just cutting prefixes off the keys (before . inclusive):

result_str = '[{"abc.xyz": "80983098429842","dev.uvw": 898420920},' \
             '{"abc.xyz": "80983098429843","dev.uvw": 898420921},{"abc.xyz": "80983098429844","dev.uvw": 898420922}]'
data = json.loads(result_str)
label_map = {"xyz": "xyz_1", "uvw": "uvw_1"}
data = [{label_map[k[k.find('.')   1:]]:v for k, v in d.items()} for d in data]
print(data)

alternatively k[k.find('.') 1:] can also be replaced with k.split('.')[1]


[{'xyz_1': '80983098429842', 'uvw_1': 898420920}, {'xyz_1': '80983098429843', 'uvw_1': 898420921}, {'xyz_1': '80983098429844', 'uvw_1': 898420922}]
  • Related