将两个字典添加到json中

时间:2018-09-26 12:01:41

标签: python json pandas dictionary

我正在尝试在Python中将两个字典一个接一个地写到JSON中。 我制作了两个看起来像---

的字典
dictionary_quant =
{'dmin': [0.003163, 14.325], 'magNst': [0.0, 414.0], 'horizontalError': [0.12, 12.9], 'nst': [3.0, 96.0], 'depth': [-3.09, 581.37], 'latitude': [-43.3468, 67.1524], 'rms': [0.0, 1.49], 'depthError': [0.0, 32.0], 'magError': [0.0, 1.34], 'mag': [-0.57, 6.9], 'gap': [18.0, 342.0], 'longitude': [-179.8024, 179.3064]}

dictionary_categorical = 
{'magType': ['ml', 'md', 'mb', 'mb_lg', 'mwr', 'Md', 'mwb', nan, 'mww'], 'net': ['ci', 'nc', 'us', 'ak', 'mb', 'uw', 'nn', 'pr', 'se', 'nm', 'ismpkansas', 'hv', 'uu'], 'type': ['earthquake', 'explosion'], 'status': ['reviewed', 'automatic'], 'locationSource': ['ci', 'nc', 'us', 'ak', 'mb', 'uw', 'nn', 'pr', 'se', 'nm', 'ismp', 'hv', 'uu', 'ott', 'guc'], 'magSource': ['ci', 'nc', 'us', 'ak', 'mb', 'uw', 'nn', 'pr', 'se', 'nm', 'ismp', 'hv', 'uu', 'ott', 'guc']}

我正在尝试写一个看起来像---

的json
data = [
            {
               'name' : 'dmin',
               'type' : 'quant',
               'minmax' : [0.003163, 14.325]
            },
            { 
               'name' : 'magNSt',
               'type' : 'quant',
               'minmax' : [0.0, 414.0]
             },
             {....},
             {....},
             {  
                'name' : 'magType',
                'type' : 'categor',
                'categories' : ['ml', 'md', 'mb', 'mb_lg', 'mwr', 'Md', 'mwb', nan, 'mww']
              },
              {
                 'name' : 'net',
                'type' : 'categor',
                'categories' : ['ci', 'nc', 'us', 'ak', 'mb', 'uw', 'nn', 'pr', 'se', 'nm', 'ismpkansas', 'hv', 'uu']
               }
]

2 个答案:

答案 0 :(得分:0)

假设确切的输出格式可以灵活(请参见下面的注释),则可以按照以下步骤进行操作。

add.ctp

答案 1 :(得分:0)

假设您事先知道每个后续词典的type,则可以执行以下操作:

def format_data(data, data_type, value_name):
    return [{'name': key, 'type': data_type, value_name: val} for key, val in data.items()]

其中data是您的dictdata_typequantcategor,而value_nameminmax或{ {1}}。

然后,总和为:

categories