S
S
Sergey Mironov2021-12-01 22:21:56
Python
Sergey Mironov, 2021-12-01 22:21:56

How to collect an array by id in python?

There is such a table
id --product_id --- name
1 ---- 65 ---- name1
2 ---- 65 ---- name2
3 ---- 65 ---- name3
4 ---- 66 ---- name4
5 ---- 66 ---- name5

Need to get this in python

Array
(
    [65] => Array
        (
            [0] => Array ([name] => name1)
            [1] => Array ([name] => name2)
            [2] => Array ([name] => name3)
         )
    [66] => Array
        (
            [0] => Array ([name] => name4)
            [1] => Array ([name] => name5)
         )


In php it would look like this:

$products = $mysqli->query("SELECT * FROM table_name");

$pr = array();

foreach($products as $product) {
$pr[$product['product_id']][] = array(
"name" => $product['name']
);
}

print_r($pr);


How to do it in python?

So far I've settled on this:

dbcursor.execute("SELECT *  FROM table_name")
results = dbcursor.fetchall()

products = {}

for result in results:
  products[result[1]] = result


Then I try to work with what happened

for product in products:
print(product)

//65
//66

Gives out the product id and that's it

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Viktor T2, 2021-12-02
@zevem

In Python, the analog of this would be a dictionary of lists:

results = cur.fetchall()

result = {} # результирующий словарь

for row in results:
    
    product_id = row[1]
    name = row[2]
        
    pred_list = result.get(product_id)   # получаем из результата список имен
                                         # относящихся к данному product_id
                                       
    if not pred_list:                    # если в результате списка еще нет
        pred_list = [name]               # создаем список
    else:                                # если список есть
        pred_list.append(name)           # добавляем имя в список
    
    result.update({product_id:pred_list}) # обновляем результирующий словарь 
    
print(result)
print(result[65])
print(result[65][1])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question