Home > Software design >  Python unexpected output in for loop
Python unexpected output in for loop

Time:04-27

I have a JSON file with a config schedules.json which contains information about a pattern and a pair of users as such:

{
    "pattern": [
        [2, "john", "jane"],
        [2, "sam", "bob"],
        [3, "john", "jane"],
        [2, "sam", "bob"],
        [2, "john", "jane"],
        [3, "sam", "bob"]
    ]
}

The idea is that for the number found in the first index, a json object will be created for each user in this list for the number of times found in the number. i.e:
for a pattern [2,"john","jane"], a json object for john and jane will be created 2 times each.
for a pattern [3,"john","jane"], a json object for john and jane will be created 3 times each etc...

The python code is below:

shift_rota = []

schedule_layers_template = {
    "morning_user": "",
    "night_user": ""
}

# Load the schedules config file
with open('config/schedules.json') as f:
    
    schedules = json.load(f)
    
    for pattern in schedules['pattern']:
                    
        # Get the number of occurrences
        occurence = int(pattern[0])
        
        # Remove occurence from list
        pattern.pop(0)
        
        morning_shift_user = pattern[0]
        night_shift_user = pattern[1]
        
        for _ in range(0, occurence):
            
            my_template = schedule_layers_template
        
            my_template['morning_user'] = morning_shift_user
            
            # Append schedule layer to list
            shift_rota.append(my_template)
        
            my_template['night_user'] = night_shift_user
            
            # Append schedule layer to list
            shift_rota.append(my_template)
            
print(f"Final shift rota {shift_rota}")

The problem here is that the final output is returning this:

Final shift rota [{'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}, {'morning_user': 'sam', 'night_user': 'bob'}]

The final output is repeating the user sam and bob for some reasons. Can someone please help ?

CodePudding user response:

PFB modified code which is working fine.

Here, we should create a copy of schedule_layers_template and then assign it to my_template.

import json


shift_rota = []
schedule_layers_template = {
    "morning_user": "",
    "night_user": ""
}
# Load the schedules config file
with open('schedules.json') as f:
    schedules = json.load(f)
    for pattern in schedules['pattern']:
        # Get the number of occurrences
        occurence = int(pattern[0])
        # Remove occurence from list
        pattern.pop(0)
        morning_shift_user = pattern[0]
        night_shift_user = pattern[1]
        for _ in range(0, occurence):
            my_template = schedule_layers_template.copy()
            my_template['morning_user'] = morning_shift_user
            my_template['night_user'] = night_shift_user
            # Append schedule layer to list
            shift_rota.append(my_template)
print(f"Final shift rota {shift_rota}")

CodePudding user response:

I was able to fix it by using deepcopy. Sample code below:

import copy

...

with open('schedules.json') as f:
schedules = json.load(f)
for pattern in schedules['pattern']:
    # Get the number of occurrences
    occurence = int(pattern[0])
    # Remove occurence from list
    pattern.pop(0)
    morning_shift_user = pattern[0]
    night_shift_user = pattern[1]
    for _ in range(0, occurence):
        my_template = copy.deepcopy(schedule_layers_template)
        my_template['morning_user'] = morning_shift_user
        my_template['night_user'] = night_shift_user
        # Append schedule layer to list
        shift_rota.append(my_template)
print(f"Final shift rota {shift_rota}")

CodePudding user response:

To avoid issues of having to copy it would be easier to move the template into the for loop and run

shift_rota = []
with open('schedules.json') as f:
    
    schedules = json.load(f)
    
    for pattern in schedules['pattern']:
        
        # Get the number of occurrences
        occurence = int(pattern[0])
        
        for _ in range(0,occurence):
            
            schedule_layers_template = {
                "morning_user": pattern[1],
                "night_user": pattern[2]
            }
            shift_rota.append(schedule_layers_template)
        
            
            
pprint(shift_rota)
  • Related