Home > Back-end >  How to iterate a list of dictionaries to a desired format for API consumption
How to iterate a list of dictionaries to a desired format for API consumption

Time:10-31

Please guys,How do I iterate this list and group some keys and values based on common keys 

and values using python?

I have a Jsonresponse that needs to be consumed by an API in a strutured order. I have looked up this platform and have seen many examples and have tried most of them to no avail and have decided to bring the problem down here for you guys to help me out. I am new to python.

input
[
    {"id": "3", "name": "John",
        "team": "corinthians", "coach": "Chris"},
    {"id": "2", "name": "Ben",
     "team": "palmeiras", "coach": "Aron"},
    {"id": "6", "name": "Frank",
     "team": "palmeiras", "coach": "Aron"}, 
    {"id": "7", "name": "Evan",
     "team": "corinthians", "coach": "Chris"}, 
    {"id": "1", "name": "Micheal",
     "team": "palmeiras", "coach": "Aron"},
    {"id": "10", "name": "Zack",
     "team": "santos", "coach": "David"}

] 

Expected output

The players are grouped by their team and coach reducing the need of repeating a player to the same  team and coach every time.

I need to present the data in this format.kindly help me out guys.Thanks

[{"players": 
            [{"id": "3", "name": "John"}, {"id": "7", "name": "Evan"}], "team": "corinthians",
"coach": "Chris"},
        {"players": [{"id": "2", "name": "Ben"}, {"id": "6", "name": "Frank"}, {"id": "1", 
"name": "Micheal"}], "team": "palmeiras", "coach": "Aron"}, 
        {"players": [{"id": "10", "name": "Zack"}], "team": "santos", "coach": "David"}]
             

CodePudding user response:

This code will save the output you want in the result variable.

input = [
    {"id": "3", "name": "John",
        "team": "corinthians", "coach": "Chris"},
    {"id": "2", "name": "Ben",
     "team": "palmeiras", "coach": "Aron"},
    {"id": "6", "name": "Frank",
     "team": "palmeiras", "coach": "Aron"}, 
    {"id": "7", "name": "Evan",
     "team": "corinthians", "coach": "Chris"}, 
    {"id": "1", "name": "Micheal",
     "team": "palmeiras", "coach": "Aron"},
    {"id": "10", "name": "Zack",
     "team": "santos", "coach": "David"}]

result = []
teamsAdded = set()
for player in input:
    if (player['team'] not in teamsAdded):
        teamsAdded.add(player['team'])
        result.append({"team": player['team'], "coach": player['coach'], "players": [{"id": player['id'], "name": player['name']}]})
    else:
        for team in result:
            if team['team'] == player['team']:
                team['players'].append({"id": player['id'], "name": player['name']})
  •  Tags:  
  • list
  • Related