Reputation: 6175
I am fetching rows from the database and wish to populate a multi-dimensional dictionary.
The php version would be roughly this:
foreach($query as $rows):
$values[$rows->id][] = $rows->name;
endforeach;
return $values;
I can't seem to find out the following issues:
What is the python way to add keys to a dictionary using an automatically numbering e.g. $values[]
How do I populate a Python dictionary using variables; using, for example, values[id] = name, will not add keys, but override existing.
I totally have no idea how to achieve this, as I am a Python beginner (programming in general, actually).
Upvotes: 1
Views: 536
Reputation: 319621
Just a general note:
Upvotes: 4
Reputation:
You can do:
from collections import defaultdict
values = defaultdict(list)
for row in query:
values[row.id].append(row.name)
return values
Edit: forgot to return the values.
Upvotes: 1
Reputation: 798716
values = collections.defaultdict(list)
for rows in query:
values[rows.id].append(rows.name)
return values
Upvotes: 8
Reputation: 67019
all_rows=[]
for row in query:
all_rows.append(row['col'])
print(all_rows)
Upvotes: 2