【问题标题】:Building dictionary dynamically from json config从 json 配置动态构建字典
【发布时间】:2021-10-26 11:31:21
【问题描述】:

我有一个来自用户的输入列表和一个标准配置。只有 user_input 可以更改。基于 user_input ,只需要在字典中选择所需的数据。即大部分配置将保持原样,只是根据 user_input 过滤水果。


user_input = ['Apple','Grapes','Watermelon']
superset_config = """
[   
    {
     "input":"source_1",
     "operation":"add",
     "fruits": {
               "Apple":"Red",
               "Grapes": ["Red","Yellow"],
               "Orange": "Yellow"
               },
        "output":"target_1"
    },
    {
     "input":"source_2",
     "fruits": { "Watermelon":"green"},
     "output":"target_2"
    }    
]
"""

期望的结果:只需从水果中删除“橙色”,因为橙色不是用户输入的一部分。其余一切都是一样的。

[   
    {
     "input":"source_1",
     "operation":"add",
     "fruits": {
               "Apple":"Red",
               "Grapes": ["Red","Yellow"]
               },
        "output":"target_1"
    },
    {
     "input":"source_2",
     "fruits": { "Watermelon":"green"},
     "output":"target_2"
    }    
]

变换:

import json
superset_definitions = json.loads(superset_config)
superset_definitions    

filtered_common_defintion = []
for each_input in user_input:
    for each_node in superset_definitions:
        if  each_input in each_node['fruits'].keys():
            temp_dictionary = {}
            temp_dictionary[each_input] = each_node['fruits'][each_input]
            filtered_common_defintion.append(temp_dictionary)
filtered_common_defintion

上面的代码对水果执行过滤,但我不确定如何捕获配置的剩余元素。有人可以指导一下吗?

【问题讨论】:

  • 创建each_input 的副本,然后过滤新输入中的水果,然后将其附加到您的filtered_common_definition

标签: python json python-3.x dictionary


【解决方案1】:

你可以使用 Python 的字典理解

for each in superset_definitions:
    each['fruits'] = {k: v for k, v in each['fruits'].items() if k in user_input}

【讨论】:

    【解决方案2】:

    您可以使用json.load将JSON字符串转换为python字典,然后迭代字典列表,并创建一个临时字典来保存值,如果键是fruits,则只取@987654323中的键@,以及字典中的对应值,否则,只需将其存储在临时字典中,最后,将每个这样的字典附加到结果列表中:

    result = []
    for d in json.loads(superset_config):
        temp = {}
        for k in d:
            if k=='fruits':
                fruits = {key:value for key,value in d[k].items() if key in user_input}
                temp[k] = fruits
            else:
                temp[k] = d[k ]
        result.append(temp)
    

    输出:

    [{'input': 'source_1',
      'operation': 'add', 
      'fruits': {'Apple': 'Red', 
                 'Grapes': ['Red', 'Yellow']
                 },
      'output': 'target_1'},
     {'input': 'source_2',
      'fruits': {'Watermelon': 'green'
                 },
      'output': 'target_2'}]
    

    【讨论】:

    • 不要使用更新来为键赋值,即mydict.update({key:value})应该只是mydict[key] = value
    • @juanpa.arrivillaga,是的,可以做到。但我通常习惯于update,因为它允许通过字典解包分配多个键/值。无论如何,我已经根据您的建议更新了解决方案。
    【解决方案3】:

    这是另一种方法:

    import json
    import copy
    user_input = ['Apple','Grapes','Watermelon']
    superset_config = """
    [   
        {
         "input":"source_1",
         "operation":"add",
         "fruits": {
                   "Apple":"Red",
                   "Grapes": ["Red","Yellow"],
                   "Orange": "Yellow"
                   },
            "output":"target_1"
        },
        {
         "input":"source_2",
         "fruits": { "Watermelon":"green"},
         "output":"target_2"
        }    
    ]
    """
    
    config = json.loads(superset_config)
    
    for item in config:
        for fruit_name, fruit_value in list(item["fruits"].items()):
            if fruit_name not in user_input:
                del item["fruits"][fruit_name]
                
    print (config)
    

    输出:

    [{'input': 'source_1', 'operation': 'add', 'fruits': {'Apple': 'Red', 'Grapes': ['Red', 'Yellow']}, 'output': 'target_1'}, {'input': 'source_2', 'fruits': {'Watermelon': 'green'}, 'output': 'target_2'}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多