Izz ad-Din Ruhulessin
Izz ad-Din Ruhulessin

Reputation: 6175

Python equiv. of PHP foreach []?

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:

I totally have no idea how to achieve this, as I am a Python beginner (programming in general, actually).

Upvotes: 1

Views: 536

Answers (4)

SilentGhost
SilentGhost

Reputation: 319621

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

Upvotes: 4

user32117
user32117

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

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798716

values = collections.defaultdict(list)
for rows in query:
  values[rows.id].append(rows.name)
return values

Upvotes: 8

rook
rook

Reputation: 67019

   all_rows=[] 
   for row in query:
       all_rows.append(row['col'])
   print(all_rows)

Upvotes: 2

Related Questions