Home > other >  Creating two different Dictionaries from the original
Creating two different Dictionaries from the original

Time:07-18

t = p.copy()
u = p.copy()

#split the data by events and participant frames
def remove_events(dictionary):
    for frame in dictionary['info']['frames']:
        del frame['events']
    return dictionary

def remove_participantframes(dictionary):
    for frame in dictionary['info']['frames']:
        del frame['participantFrames']
    return dictionary

t = remove_participantframes(t)
u = remove_events(u)


with open('removed_participantframes.txt', 'w') as f:
    json.dump(t, f, indent=2)
with open('removed_events.txt', 'w') as f:
    json.dump(u, f, indent=2)

I have a starting dictionary p and I want to do two different operations remove_participantframes and remove_events to create two new dictionaries t and u. Currently when uploading t and u they both have the remove_participantframes and remove_eventsoperations applied to them.

I would like to have two different dictionaries as a result of the operations.

CodePudding user response:

When you use copy.copy(), the new object is created. However, the children were not copied but referenced. So, in your case if you want to have two different dictionaries, you should use copy.deepcopy().

The docs explain the difference between them.

CodePudding user response:

The problem is that you are not really making a copy of the list:

id(p['info']['frames']), id(t['info']['frames']), id(u['info']['frames'])

You can solve it by using deepcopy:

from copy import deepcopy
t = deepcopy(p)
u = deepcopy(p)

Or by generating new dicts:

def remove_events(dictionary):
    return {
        'info': {
            'frames': [
                {k: v for k, v in frame.items() if k != 'events'}
                for frame in dictionary['info']['frames']
            ]
        }
    }

def remove_participantframes(dictionary):
    return {
        'info': {
            'frames': [
                {k: v for k, v in frame.items() if k != 'participantFrames'}
                for frame in dictionary['info']['frames']
            ]
        }
    }
  • Related