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  
3
  • 1
    This may help: Python sorting by multiple criteria Commented Oct 24, 2021 at 2:54
  • Can you post a code snippet Commented Oct 24, 2021 at 4: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. Commented Oct 24, 2021 at 18:55

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for taking the time to respond. I am still having difficulty wrapping my head around lists, and dict, etc. vs PHP arrays.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.