FamLamb
FamLamb

Reputation: 13

Python: Nested For Loop Overwriting Entire Dictionary When Looping Through List

Goal:

I'm trying to iterate on a copy of a nested dictionary (based on a simple JSON schema) to build individual JSON payloads for a web server requests that represents a team and its members.

Each payload is sourced from a dictionary outside of the loop containing the team as a key and the id of its users as values.

Issue:

I'm able to successfully copy the source dictionary and create the team dictionary including its 1st member, but on the 2nd iteration of the list to add additional members the first member is overwritten instead of the 2nd being added to the dictionary payload

This is my first time working with nested dictionaries so any tips would be highly appreciated.

# source dictionary

teams_dict = {'Boston':['1234','5678'],
              'Atlanta':['9876','4321']}

# schema to be modified

payload_schema = {"data":
                  {"id":None,"type":"teams","attributes":
                   {"name":None},"relationships":
                   {"members":{"data":[{"id":None,"type":"users"}]}}}}

# loop

for team, members in teams_dict.items():
    team_load = deepcopy(payload_schema)
    team_load['data']['attributes']['name']=team
    #print(f"Now creating team {team}")
    for member in members:
        team_load['data']['relationships']['members']['data'][0]['id']=member
        team_load['data']['relationships']['members']['data'][0]['type']='users'
        print(team_load)
        #print(f"Added user id {member} to payload")

I end up with a payload only containing the 2nd member since the first is overwritten:

print(team_load)

{'data': {'id': None, 'type': 'teams', 'attributes': {'name': 'Atlanta'}, 'relationships': {'members': {'data': [{'id': '4321', 'type': 'users'}]}}}}

Ideally it would look like this:

print(team_load)

{'data': {'id': None, 'type': 'teams', 'attributes': {'name':'Atlanta'}, 'relationships': {'members': {'data': [{'id': '9876','type': 'users'},{'id': '4321','type': 'users'}]}}}}

Upvotes: 0

Views: 411

Answers (1)

Dale
Dale

Reputation: 544

The problem is that you're always writing to index 0 with this:

team_load['data']['relationships']['members']['data'][0]['id']=member
team_load['data']['relationships']['members']['data'][0]['type']='users'

this is a list:

team_load['data']['relationships']['members']['data']

so you need to append to it each time.

Since you're dealing with nested objects, I'd make the member info another object and remove it from the payload schema:

payload_schema = {"data":
              {"id":None,"type":"teams","attributes":
               {"name":None},"relationships":
               {"members":{"data":[]}}}}
member_schema = {"id":None,"type":"users"}

Then in the inner loop:

for member in members:
    member_load = deepcopy(member_schema)

    member_load['id']=member

    team_load['data']['relationships']['members']['data'].append(member_load)
    print(team_load)

you don't need to set the type to "users" since it's already set in the schema, but you could set it to a different value if you wanted to.

Hope this helps!

Upvotes: 1

Related Questions