views:

102

answers:

4

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).

+1  A: 
   all_rows=[] 
   for row in query:
       all_rows.append(row['col'])
   print(all_rows)
Rook
+6  A: 
values = collections.defaultdict(list)
for rows in query:
  values[rows.id].append(rows.name)
return values
Ignacio Vazquez-Abrams
A: 

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.

Luiz Damim
+1  A: 

Just a general note:

  1. Python's dictionaries are mappings without order, while adding numerical keys would allow "sequential" access, in case of iteration there's no guarantee that order will coincide with the natural order of keys.
  2. It's better not to translate from PHP to Python (or any other language), but rather right code idiomatic to that particular language. Have a look at the many open-source code that does the same/similar things, you might even find a useful module (library).
SilentGhost