简体   繁体   English

定制的OrderedDict格式并转移到字典中

[英]customized OrderedDict format and transfer into dictionary

I have an issue about how to customize OrderedDict format and convert them into a json or dictionary format(but be able to reset the key names and the structure). 我有一个关于如何自定义OrderedDict格式并将其转换为json或字典格式的问题(但是能够重置键名称和结构)。 I have the data below: 我有以下数据:

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

...However, I want to change the format like this: ...但是,我想这样更改格式:

{
 "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"
}

I will be really appreciate your help. 非常感谢您的帮助。 Basically the output I got is pretty flat. 基本上我得到的输出是相当平坦的。 But I want to customize the structure. 但是我想自定义结构。 The original structure is 原始结构是

OrderedDict([('index', 'cfs_fsd_00001'),('host', 'GIISSP707').....]). OrderedDict([('index','cfs_fsd_00001'),('host','GIISSP707').....])。

The output I want to achieve is {"servarname"{"index":"cfs_fsd_00001","host":"GIISSP707"},...... 我要实现的输出是{“ servarname” {“ index”:“ cfs_fsd_00001”,“ host”:“ GIISSP707”},......

You can simply reference the result dict with the respective keys that you want your target data structure to have: 您可以简单地使用您希望目标数据结构具有的各个键来引用result字典:

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

No sure how flexible you need for your method. 不确定您的方法需要多大的灵活性。 I assume you have a few common keys in your OrderedDict and you want to find the metric there, then reformat them into a new dict. 我假设您在OrderedDict中有一些通用键,并且想要在此处找到指标,然后将其重新格式化为新的dict。 Here is a short function which is implemented in python 3 and I hope it could help. 这是在python 3中实现的简短函数,希望对您有所帮助。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM