Harry Lingard-Bright
Harry Lingard-Bright

Reputation: 51

Array of Arrays grouped by Key to be displayed as a table Python

pretty new to python so apologies if I'm going about this wrong! I am building a website on Flask that gets information from the fantasy premier league api for me and my friends, and displays the resulting scores by week in a table. I have retrieved the scores and manipulated them such that I have the following array:

[
[{'GameWeek': 1, 'JH Score': 71}, {'GameWeek': 1, 'Harry Score': 70}, {'GameWeek': 1, 'Alex Score': 64}], 
[{'GameWeek': 2, 'JH Score': 80}, {'GameWeek': 2, 'Harry Score': 41}, {'GameWeek': 2, 'Alex Score': 52}],
[{'GameWeek': 3, 'JH Score': 40}, {'GameWeek': 3, 'Harry Score': 60}, {'GameWeek': 3, 'Alex Score': 46}], 
[{'GameWeek': 4, 'JH Score': 41}, {'GameWeek': 4, 'Harry Score': 29}, {'GameWeek': 4, 'Alex Score': 65}], 
[{'GameWeek': 5, 'JH Score': 65}, {'GameWeek': 5, 'Harry Score': 56}, {'GameWeek': 5, 'Alex Score': 65}], 
[{'GameWeek': 6, 'JH Score': 63}, {'GameWeek': 6, 'Harry Score': 54}, {'GameWeek': 6, 'Alex Score': 38}], 
[{'GameWeek': 7, 'JH Score': 47}, {'GameWeek': 7, 'Harry Score': 65}, {'GameWeek': 7, 'Alex Score': 46}], 
[{'GameWeek': 8, 'JH Score': 87}, {'GameWeek': 8, 'Harry Score': 70}, {'GameWeek': 8, 'Alex Score': 88}]
]

I would like to do the following:

  1. Group those key/value pairs by gameweek, i.e.
{'GameWeek': 1, 'JH Score': 71, 'Harry Score': 70, 'Alex Score': 64},
{'GameWeek': 2, 'JH Score': 80, 'Harry Score': 41, 'Alex Score': 52},

etc

  1. Display this information in a table in browser, of the structure
 GameWeek    JH Score   Harry Score   Alex Score
   1            71           70            64
   2            80           41            52

etc

Thank you in advance for your help. Apologies if I have not been clear enough!

Upvotes: 4

Views: 60

Answers (1)

Quinn
Quinn

Reputation: 96

Here, try this code below if you re using Python 3.5+:

res = []

for gmwks in arr:
    wk = {}
    for dic in gmwks:
        wk = {**wk, **dic}
    res.append(wk)

This will combine all dicts as you wanted.

doc: https://stackoverflow.com/a/26853961/10929089

Upvotes: 3

Related Questions