【问题标题】:Add two dictionaries into a json将两个字典添加到 json
【发布时间】:2023-04-08 13:40:01
【问题描述】:

我正在尝试在 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']
               }
]

【问题讨论】:

  • 所以你隐式需要合并两个字典,同时检查字典中某个位置的数据类型(我的意思是[0.003163, 14.325] 是quant 而['ml', 'md', 'mb', ... ] 是categor) ?还是您事先知道(正如您的字典名称所暗示的那样)?
  • 另外,到目前为止,您尝试了什么?
  • 是的,我通过一些先决条件发现,所以在dictionary_quant 中都是定量变量,dictionary_categor 都是分类的
  • stackoverflow.com/questions/17043860/…。我试过这个例子,但它给了我在其中添加类型的错误
  • 你试过什么?你知道如何获取字典的项目((key, value) 对)吗?从一个特定的(key, value) 对中,你能以你想要的形式构造一个字典吗?给定一个对列表和一种将一对转换为您想要的数据的方法,您知道如何将它们组合以获得新的字典列表吗?您知道如何将两个列表(您必须以不同方式处理 quant 和 categor)合并为一个列表吗?

标签: python json pandas dictionary


【解决方案1】:

假设确切的输出格式可以是灵活的(见下面的评论),这可以如下完成。

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

【讨论】:

    【解决方案2】:

    假设您事先知道每个后续字典的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')
    

    【讨论】:

      猜你喜欢
      • 2015-03-21
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 2017-05-31
      • 2014-12-16
      相关资源
      最近更新 更多