将python字典值追加到python列表

f0ofjuux  于 2023-02-02  发布在  Python
关注(0)|答案(1)|浏览(192)

我正在尝试处理我的API结果字符串,结果字符串的格式如下所示。我的目标是将这些值添加到一个列表中,其中列表的每个元素都将是一个字典。

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

然而,我的代码多次返回一个只包含最后一个元素的列表,而不是每个元素只包含一次。
下面是我的代码:

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)

预期输出:

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

电流输出:

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

68bkxrlz1#

您所需要的只是从键中去掉前缀(包括.之前的键):

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)

或者k[k.find('.') + 1:]也可以用k.split('.')[1]代替

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

相关问题