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

Time:04-21

I have a problem. I have a dict my_Dict. This is somewhat nested. However, I would like to 'clean up' the dict my_Dict, by this I mean that I would like to separate all nested ones and also generate a unique ID so that I can later find the corresponding object again. For example, I have detail: {...}, this nested, should later map an independent dict my_Detail_Dict and in addition, detail should receive a unique ID within my_Dict. Unfortunately, my list that I give out is empty. How can I remove my slaughtered keys and give them an 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]

What I have

{'_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'}]}}}

What I want

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}

CodePudding user response:

If I understand you correctly, you wish to automatically make each nested dictionary it's own variable, and remove it from the main dictionary.

Finding the nested dictionaries and removing them from the main dictionary is not so difficult. However, automatically assigning them to a variable is not recommended for various reasons. Instead, what I would do is store all these dictionaries in a list, and then assign them manually to a variable.

# 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

CodePudding user response:

The following code snippet will solve what you are trying to do:

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