Home > Enterprise >  Remove nested element occurs twice but should be only once
Remove nested element occurs twice but should be only once

Time:04-22

I have a problem. I want to remove all nested elements inside a dict. But unfortunately my code does not work. Every nested element occurs twice, but it should be occurs only once. What is the problem for that?

Method

def nested_dict(dictionaries):
    
    my_list = []
    for my_Dict in dictionaries:
      my_new_dict = {}
      
      for key in my_Dict.keys():
          if isinstance(my_Dict[key], dict):
              idx = str(uuid.uuid4())
              my_Dict[key]["__id"] = idx
              my_new_dict[key] = my_Dict[key]
              my_Dict[key] = idx
              my_list.append(my_new_dict)
      
    return my_list

Running example

import uuid
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'}]
            }
        }   
 }

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

def nested_dict(dictionaries):
    
    my_list = []
    for my_Dict in dictionaries:
      my_new_dict = {}
      
      for key in my_Dict.keys():
          if isinstance(my_Dict[key], dict):
              idx = str(uuid.uuid4())
              my_Dict[key]["__id"] = idx
              my_new_dict[key] = my_Dict[key]
              my_Dict[key] = idx
              my_list.append(my_new_dict)
      
    return my_list

result = nested_dict(dictionaries)
result

[OUT]

[{'data': {'__id': '46f4eb3d-977c-4da4-a99c-c9bfa831b96e'},
  'detail': {'selector': {'number': '12312',
    'isTrue': True,
    'requirements': [{'type': 'customer', 'requirement': '1'}]},
   '__id': 'fad4053e-75e5-4a03-93b6-67e0df814d23'}},
 {'data': {'__id': '46f4eb3d-977c-4da4-a99c-c9bfa831b96e'},
  'detail': {'selector': {'number': '12312',
    'isTrue': True,
    'requirements': [{'type': 'customer', 'requirement': '1'}]},
   '__id': 'fad4053e-75e5-4a03-93b6-67e0df814d23'}},
 {'data2': {'__id': '6afcf48e-508c-476b-98f3-9bf1e8370fb4'},
  'detail2': {'selector': {'number': '12312',
    'isTrue': True,
    'requirements': [{'type': 'customer', 'requirement': '1'}]},
   '__id': '2d4745ea-decd-45dc-aa0b-7bea5c449c34'}},
 {'data2': {'__id': '6afcf48e-508c-476b-98f3-9bf1e8370fb4'},
  'detail2': {'selector': {'number': '12312',
    'isTrue': True,
    'requirements': [{'type': 'customer', 'requirement': '1'}]},
   '__id': '2d4745ea-decd-45dc-aa0b-7bea5c449c34'}}]

What I want

[{'data': {'__id': '46f4eb3d-977c-4da4-a99c-c9bfa831b96e'},
  'detail': {'selector': {'number': '12312',
    'isTrue': True,
    'requirements': [{'type': 'customer', 'requirement': '1'}]},
   '__id': 'fad4053e-75e5-4a03-93b6-67e0df814d23'}},
 {'data2': {'__id': '6afcf48e-508c-476b-98f3-9bf1e8370fb4'},
  'detail2': {'selector': {'number': '12312',
    'isTrue': True,
    'requirements': [{'type': 'customer', 'requirement': '1'}]},
   '__id': '2d4745ea-decd-45dc-aa0b-7bea5c449c34'}}]

CodePudding user response:


import uuid
import json
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'}]
            }
        }   
 }

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

def nested_dict(dictionaries):
    
    my_list = []
    for my_Dict in dictionaries:
      my_new_dict = {}
      
      for key in my_Dict.keys():
          if isinstance(my_Dict[key], dict):
              idx = str(uuid.uuid4())
              my_Dict[key]["__id"] = idx
              my_new_dict[key] = my_Dict[key]
              my_Dict[key] = idx
      my_list.append(my_new_dict)
      
    return my_list


output:
[
    {
        "data": {
            "__id": "5c6769cf-01e5-4f5d-acfa-622472163aba"
        },
        "detail": {
            "selector": {
                "number": "12312",
                "isTrue": true,
                "requirements": [
                    {
                        "type": "customer",
                        "requirement": "1"
                    }
                ]
            },
            "__id": "d167277f-4d02-4d53-934b-131187f6f214"
        }
    },
    {
        "data2": {
            "__id": "e9182913-c2fc-4d60-adb8-b0b8274faf50"
        },
        "detail2": {
            "selector": {
                "number": "12312",
                "isTrue": true,
                "requirements": [
                    {
                        "type": "customer",
                        "requirement": "1"
                    }
                ]
            },
            "__id": "46e6be7b-8903-4d2a-a768-f6b24fcc5d31"
        }
    }
]

only minor changes needed that is you are appending the list within inner for loop but you should do it at outer for loop level. I have pasted the code with output which I got

CodePudding user response:

I think it is because my_new_dict is holding an object that is changed by the time it appends to the list.

def nested_dict(dictionaries):
    my_list = []
    for my_Dict in dictionaries:
        my_new_dict = {}

        for key in my_Dict.keys():
            if isinstance(my_Dict[key], dict):
                idx = str(uuid.uuid4())
                my_Dict[key]["__id"] = idx
                my_new_dict[key] = my_Dict[key]
                my_Dict[key] = idx
                my_list.append({key: my_new_dict[key]})
                print(my_list)

    return my_list
  • Related