Answer the question
In order to leave comments, you need to log in
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)
)
$products = $mysqli->query("SELECT * FROM table_name");
$pr = array();
foreach($products as $product) {
$pr[$product['product_id']][] = array(
"name" => $product['name']
);
}
print_r($pr);
dbcursor.execute("SELECT * FROM table_name")
results = dbcursor.fetchall()
products = {}
for result in results:
products[result[1]] = result
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question