【问题标题】:Reaching a leaf using substring in a dictionary with multiple structures使用具有多个结构的字典中的子字符串到达​​叶子
【发布时间】:2021-12-11 03:42:14
【问题描述】:

我有这样一个 json 文件,它结合了所有以前的数据存储版本。一个例子是这样的:

myList = {1: {'name': 'John', 'age': '27', 'class'= '2', 'drop' = True},
          2: {'name': 'Marie', 'other_info': {'age': '22', 'class'= '3', 'dropped'= True }},
          3: {'name': 'James', 'other_info': {'age': '23', 'class'= '1', 'is_dropped'= False}},
          4: {'name': 'Lucy', 'some_info': {'age': '20', 'class'= '4', 'other_branch': {'is_dropped' = True, 'how_drop'= 'Foo'}}}}

我想访问 key 或 subkey 中包含 drop 的信息。我不知道所有的字典结构,可能有 20 个或更多。我所知道的是它们都包含“drop”这个短语。可能还有其他短语可能包含短语“drop”,但它们并不过分。如果有多滴,我可以手动调整要滴哪一个。

我尝试展平,但展平后每个字典项都有不同的键名。

我还想了解其他信息,但这些属性中的大多数也存在类似问题。

我想获取dropdroppedis_dropped 键中的True, True, False, True 值。

我怎样才能到达这个节点?

【问题讨论】:

  • 你的预期输出是什么?
  • True-True-False-True 列表。

标签: python dictionary nested substring key


【解决方案1】:

创建一个递归函数来搜索并添加到增量键。无需在安全检查中详细说明,您可以执行以下操作:

def find(input_dict, base='', search_key='drop'):
   found_paths = []
   if search_key in input_dict.keys():
      found_paths.append(base)
   for each_key in input_dict.keys():
      if isinstance(input_dict[each_key], dict):
         new_base = base + '.' + each_key
         found_paths += find(input_dict[each_key], base=new_base, search_key=search_key)
   return found_paths

【讨论】:

  • 你可以编辑这个来实现“真、真、假、真”的输出
【解决方案2】:

你可以使用递归来解决这个问题:

def get_drop(dct):
    for key, val in dct.items():
        if isinstance(key, str) and 'drop' in key and isinstance(val, bool):
            yield val
        elif isinstance(val, dict):
            yield from get_drop(val)

print(list(get_drop(myList)))

[True, True, False, True]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多