定制OrderedDict格式并转换为字典

2024-05-09 20:45:48 发布

您现在位置:Python中文网/ 问答频道 /正文

关于如何自定义OrderedDict格式并将其转换为json或dictionary格式(但是能够重置键名和结构),我遇到了一个问题。我有以下数据:

result= OrderedDict([('index', 'cfs_fsd_00001'),
                     ('host', 'GIISSP707'),
                     ('source', 'D:\\usrLLSS_SS'),
                     ('_time', '2018-11-02 14:43:30.000 EDT'),
                     ('count', '153')])

…但是,我想更改如下格式:

{
 "servarname": {
    "index": "cfs_fsd_00001",
    "host": "GIISSP707"
 },
 "times": '2018-11-02 14:43:30.000 EDT',
 "metricTags": {
    "source": 'D:\\ddevel.log'"
 },
 "metricName": "serverice count",
 "metricValue": 153,
 "metricType": "count"
}

我将非常感谢你的帮助。基本上我得到的输出是相当平坦的。但我想定制结构。原来的结构是

OrderedDict([('index','cfs\u fsd\u 00001'),('host','GIISSP707')…])。你知道吗

我要实现的输出是{“servarname”{“index”:“cfs\u fsd\u 00001”,“host”:“GIISSP707”},。。。。。。你知道吗


Tags: jsonhostsourceindexdictionary格式count结构
2条回答

您可以简单地引用resultdict和您希望目标数据结构具有的相应键:

{
    "servarname": {
        "index": result['index'],
        "host": result['host']
    },
    "times": result['_time'],
    "metricTags": {
        "source": result['source']
    },
    "metricName": "serverice count",
    "metricValue": result['count'],
    "metricType": "count"
}

不知道你的方法需要多灵活。我假设您在OrderedDict中有一些公共键,您希望在那里找到度量,然后将它们重新格式化为新的dict。你知道吗

from collections import OrderedDict
import json

def reformat_ordered_dict(dict_result):
    """Reconstruct the OrderedDict result into specific format

    This method assumes that your input OrderedDict has the following common keys: 'index',
    'host', 'source', '_time', and a potential metric whcih is subject to change (of course
    you can support more metrics with minor tweak of the code). The function also re-map the
    keys (for example, mapping '_time' to 'times', pack 'index' and 'source' into 'servarname'
    ).
    :param dict_result: the OrderedDict
    :return: the reformated OrderedDict
    """
    common_keys = ('index', 'host', 'source', '_time')
    assert all(common_key in dict_result for common_key in common_keys), (
        'You have to provide all the commen keys!')

    # write common keys
    reformated = OrderedDict()
    reformated["servarname"] = OrderedDict([
        ("index", dict_result['index']),
        ("host", dict_result['host'])
    ])
    reformated["times"] = dict_result['_time']
    reformated["metricTags"] = {"source": dict_result['source']}

    # write metric
    metric = None
    for key in dict_result.keys():
        if key not in common_keys:
            metric = key
            break

    assert metric is not None, 'Cannot find metric in the OrderedDict!'

    # don't know where you get this value. But you can customize it if needed
    # for exampe if the metric name is needed here
    reformated['metricName'] = "serverice count"
    reformated['metricValue'] = dict_result[metric]
    reformated['metricType'] = metric

    return reformated

if __name__ == '__main__':
    result= OrderedDict([('index', 'cfs_fsd_00001'),
                     ('host', 'GIISSP707'),
                     ('source', 'D:\\usrLLSS_SS'),
                     ('_time', '2018-11-02 14:43:30.000 EDT'),
                     ('count', '153')])
    reformated = reformat_ordered_dict(result)
    print(json.dumps(reformated))

相关问题 更多 >