-1

I am trying to write two dictionaries into a JSON one after another in Python. I have made two dictionaries which look like ---

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

I am trying to write a json which looks like --

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']
               }
]
gkuhu
  • 299
  • 1
  • 4
  • 17
  • 1
    So you implicitly require to merge the two dictionaries while checking the type of data that are at some position in your dictionary (I mean `[0.003163, 14.325]` is `quant` while `['ml', 'md', 'mb', ... ]` is `categor`)? Or do you know it before hand (as the names of your dictionaries suggest)? – Léopold Houdin Sep 26 '18 at 12:05
  • Also, what have you tried so far? – Léopold Houdin Sep 26 '18 at 12:12
  • Yes I find out through some preconditions, so in dictionary_quant all are quantative variables and dictionary_categor all are categorical – gkuhu Sep 26 '18 at 12:16
  • https://stackoverflow.com/questions/17043860/python-dump-dict-to-json-file. I tried this example but it gives me error of I add type in it – gkuhu Sep 26 '18 at 12:16
  • What have you tried? Do you know how to get a dictionary's items (`(key, value)` pairs)? From a particular `(key, value)` pair, could you construct a single dictionary in the form that you want? Given a list of pairs and a way to turn a pair into the data you want, do you know how to combine them to get a new list of dicts? Do you know how to combine two lists (you'll have to process `quant` and `categor` differently) into a single one? – Andrea Reina Sep 26 '18 at 12:18
  • print json.dumps([{'name': k, 'minmax': v, 'type': "quant"} for k,v in dictionary_quant.items()], indent=4) . I tried this – gkuhu Sep 26 '18 at 12:20

2 Answers2

0

Assuming that the exact output format can be flexible (see comment below), this can be done as follow.

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))
The Tahaan
  • 6,915
  • 4
  • 34
  • 54
0

Assuming you know beforehand the type of each subsequent dictionary, you could do the following:

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

where data is your dict, data_type is either quant or categor and value_name is either minmax or categories.

Then, combined that would be:

combined = format(dictionary_quant, 'quant', 'minmax') + format_data(dictionary_categorical, 'categor', 'categories')
Léopold Houdin
  • 1,515
  • 13
  • 18