Python从其他dict中的特定键创建新dict(嵌套)

2024-09-28 21:39:06 发布

您现在位置:Python中文网/ 问答频道 /正文

(请注意,我搜索了这种类型的嵌套、dict和list以及keep key name和value,但找不到答案)

我正在尝试从现有的dict创建一个新的dict,其中包含我需要的特定键-值对

示例/源代码:

{
    "test1":{
        "test2":[
            
        ]
    },
    "test3":[
        
    ],
    "test4":{
        "test5":0,
        "what":{
            "in":"2",
            "out":"4"
        }
    },
    "test12":[
        {
            "in2":"a",
            "out2":"b"
        },
        {
            "in2":"a33",
            "out2":"b33"
        }
    ],
    "test9":255
}

我想选择键,例如:['test1'], ['test4'], ['test12']['in2'] 这样,dict的结果将是:

{
    "test1":{
        "test2":[
            
        ]
    },
    "test4":{
        "test5":0,
        "what":{
            "in":"2",
            "out":"4"
        }
    },
    "test12":[
        {
            "in2":"a"
        },
        {
            "in2":"a33"
        }
    ]
}

我知道可以手动操作,我想看看pythonic的方式:)

谢谢


Tags: in类型outwhatdictlistkeeptest1
2条回答

我不认为有一种“pythonic”的方法来做你想做的事情,因为嵌套dict有无限多的可能值

这是一个开始的答案,你可以适应你的需要

import copy

def _transform(source_dict: dict, keys_to_keep: list):
   dict_copy = copy.deepcopy(source_dict)  # no side-effects
   
   for key, value in source_dict.items():
       if key not in keys_to_keep:
         dict_copy.pop(key)
       elif isinstance(value, dict):
         dict_copy[key] = _transform(value, keys_to_keep)
       elif isinstance(value, list):
         dict_copy[key] = [
             _transform(el, keys_to_keep) if isinstance(el, dict) else el for el in value
         ]
   return dict_copy

使用isinstance{}尝试字典理解:

>>> {k: ([{'in2': i['in2']} for i in v] if isinstance(v, list) else v) for k, v in dct.items() if not isinstance(v, int) and v}
{'test1': {'test2': []},
 'test4': {'test5': 0, 'what': {'in': '2', 'out': '4'}},
 'test12': [{'in2': 'a'}, {'in2': 'a33'}]}
>>> 

相关问题 更多 >