1

The results of a postgres query using psycopg2 are something like this:

[(1, 20386, 3), (2, 20386, 5), (3, 20386, 5), (1, 20387, 2), (2, 20387, 2), (3, 20387, 3), (1, 20390, 3), (2, 20390, 3), (3, 20390, 3)] 

I need to reorder the result such that (in PHP at least) it would look like this:

user['20386'][1]=3  
user['20386'][2]=5  
user['20386'][3]=5  

user['20387'][1]=2  
user['20387'][2]=2  
user['20387'][3]=3  

user['20390'][1]=3  
user['20390'][2]=3  
user['20390'][3]=3  
karel
  • 5,489
  • 46
  • 45
  • 50
mick
  • 51
  • 3
  • 1
    This may help: [Python sorting by multiple criteria](https://stackoverflow.com/questions/20145842/python-sorting-by-multiple-criteria) – sj95126 Oct 24 '21 at 02:54
  • Can you post a code snippet – Michael Robellard Oct 24 '21 at 04:47
  • Obviously, the question pointed out as a duplicate has little to do with this question. Reviewers should really pay more attention when evaluating questions. – klin Oct 24 '21 at 18:55

1 Answers1

0

You can convert the data into a dict of lists:

>>> user = {}
>>> for key in {item[1] for item in data}:
...     user[key] = [item[2] for item in data if item[1] == key]

The user looks like this:

>>> user
{20386: [3, 5, 5], 20387: [2, 2, 3], 20390: [3, 3, 3]}

Note however, that lists are indexed from 0:

>>> user[20386]
[3, 5, 5]
>>> user[20386][0]
3
>>> user[20386][1]
5
klin
  • 112,967
  • 15
  • 204
  • 232
  • Thank you for taking the time to respond. I am still having difficulty wrapping my head around lists, and dict, etc. vs PHP arrays. – mick Oct 24 '21 at 15:59