4

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!

davidism
  • 121,510
  • 29
  • 395
  • 339

1 Answers1

3

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

Quinn
  • 96
  • 6
  • 1
    Of course, in Python 3.5+ they added a dict functionallity that means those 2 dictionaries will merge into one; as far as you could know, dictionaries are uniqued valued, so if you see the code, variable wk will get the wk content itself plus the actual dict. – Quinn Nov 14 '20 at 12:36