如何删除嵌套键并创建一个新的 dict 和 link 都带有一个 ID?

How can I remove nested keys and create a new dict and link both with an ID?

我有问题。我有一个字典 my_Dict。这有点嵌套。但是,我想'clean up' the dict my_Dict,我的意思是我想分离所有嵌套的,并生成一个唯一的ID,以便我以后可以再次找到相应的对象。 例如,我有 detail: {...},这是嵌套的,稍后应该映射一个独立的字典 my_Detail_Dict,此外,detail 应该在 my_Dict 中接收一个唯一的 ID。不幸的是,我给出的清单是空的。我怎样才能取出我被屠杀的钥匙并给他们一个 ID?

my_Dict = {
'_key': '1',
 'group': 'test',
 'data': {},
 'type': '',
 'code': '007',
 'conType': '1',
 'flag': None,
 'createdAt': '2021',
 'currency': 'EUR',
 'detail': {
        'selector': {
            'number': '12312',
            'isTrue': True,
            'requirements': [{
                'type': 'customer',
                'requirement': '1'}]
            }
        }   
 }


def nested_dict(my_Dict):
    my_new_dict_list = []
    for key in my_Dict.keys():
        #print(f"Looking for {key}")
        if isinstance(my_Dict[key], dict):
            print(f"{key} is nested")


            # Add id to nested stuff
            my_Dict[key]["__id"] = 1        
            my_nested_Dict = my_Dict[key]
            # Delete all nested from the key
            del my_Dict[key]
            # Add id to key, but not the nested stuff
            my_Dict[key] = 1

            my_new_dict_list.append(my_Dict[key])
        my_new_dict_list.append(my_Dict)
        return my_new_dict_list

nested_dict(my_Dict)

[OUT] []
# What I want

[my_Dict, my_Details_Dict, my_Data_Dict]

我有什么

{'_key': '1',
 'group': 'test',
 'data': {},
 'type': '',
 'code': '007',
 'conType': '1',
 'flag': None,
 'createdAt': '2021',
 'currency': 'EUR',
 'detail': {'selector': {'number': '12312',
   'isTrue': True,
   'requirements': [{'type': 'customer', 'requirement': '1'}]}}}

我想要的

my_Dict = {'_key': '1',
 'group': 'test',
 'data': 18,
 'type': '',
 'code': '007',
 'conType': '1',
 'flag': None,
 'createdAt': '2021',
 'currency': 'EUR',
 'detail': 22}


my_Data_Dict = {'__id': 18}

my_Detail_Dict = {'selector': {'number': '12312',
   'isTrue': True,
   'requirements': [{'type': 'customer', 'requirement': '1'}]}, '__id': 22}

如果我没理解错的话,您希望自动使每个嵌套字典成为自己的变量,并将其从主字典中删除。

找到嵌套词典并将它们从主词典中删除并不难。但是,出于各种原因,不建议将它们自动分配给变量。相反,我要做的是将所有这些字典存储在一个列表中,然后手动将它们分配给一个变量。

# Prepare a list to store data in
inidividual_dicts = []

id_index = 1
for key in my_Dict.keys():
    # For each key, we get the current value
    value = my_Dict[key]
    
    # Determine if the current value is a dictionary. If so, then it's a nested dict
    if isinstance(value, dict): 
        print(key + " is a nested dict")
        
        # Get the nested dictionary, and replace it with the ID
        dict_value = my_Dict[key]
        my_Dict[key] = id_index

        # Add the id to previously nested dictionary
        dict_value['__id'] = id_index
        
        
        id_index = id_index + 1 # increase for next nested dic
        
        inidividual_dicts.append(dict_value) # store it as a new dictionary
        

# Manually write out variables names, and assign the nested dictionaries to it. 
[my_Details_Dict, my_Data_Dict] = inidividual_dicts

以下代码片段将解决您要执行的操作:

my_Dict = {
'_key': '1',
 'group': 'test',
 'data': {},
 'type': '',
 'code': '007',
 'conType': '1',
 'flag': None,
 'createdAt': '2021',
 'currency': 'EUR',
 'detail': {
        'selector': {
            'number': '12312',
            'isTrue': True,
            'requirements': [{
                'type': 'customer',
                'requirement': '1'}]
            }
        }   
 }

def nested_dict(my_Dict):
    # Initializing a dictionary that will store all the nested dictionaries
    my_new_dict = {}
    idx = 0
    for key in my_Dict.keys():
        # Checking which keys are nested i.e are dictionaries
        if isinstance(my_Dict[key], dict):
            # Generating ID
            idx += 1

            # Adding generated ID as another key
            my_Dict[key]["__id"] = idx

            # Adding nested key with the ID to the new dictionary
            my_new_dict[key] = my_Dict[key]

            # Replacing nested key value with the generated ID
            my_Dict[key] = idx
    
    # Returning new dictionary containing all nested dictionaries with ID
    return my_new_dict

result = nested_dict(my_Dict)
print(my_Dict)

# Iterating through dictionary to get all nested dictionaries
for item in result.items():
    print(item)