Добавьте два словаря в JSON - PullRequest
       1

Добавьте два словаря в JSON

0 голосов
/ 26 сентября 2018

Я пытаюсь записать два словаря в JSON один за другим в Python.Я сделал два словаря, которые выглядят как ---

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 голосов
/ 26 сентября 2018

Предполагая, что вы заранее знаете 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 - ваш dict, data_type - либо quant, либоcategor и value_name это либо minmax, либо categories.

Тогда, вместе это будет:

combined = format(dictionary_quant, 'quant', 'minmax') + format_data(dictionary_categorical, 'categor', 'categories')
0 голосов
/ 26 сентября 2018

Предполагая, что точный формат вывода может быть гибким (см. Комментарий ниже), это можно сделать следующим образом.

import 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]}

# Replaced the undefined keyword / variable "nan" with None
dictionary_categorical = {'magType': ['ml', 'md', 'mb', 'mb_lg', 'mwr', 'Md', 'mwb', None, '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']}

#Start with an empty data list
data = []

# Add each item in dictionary_quant with type set to "quant" and the 
# value on key minmax
for k, v in dictionary_quant.items():
    data.append({'type': 'quant',
                 'name': k,
                 'minmax': v})

# Add each item in dictionary_categorical with type set to "categor" 
# and the value on key "categories"
for k, v in dictionary_categorical.items():
    data.append({'type': 'categor',
                 'name': k,
                 'categories': v})

# Note: The json.dumps() function will output list attribute elements 
# one-per-line when using indented output.
print(json.dumps(data, indent=4))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...