-1

Could someone help me find a way to do the function below in python?

I do think I could use a for loop with indexes and do it that way but there might be an easier method with pythons list comprehension

let rows = [['10kg', '12.5', '1.25', '8'], 
  ['25kg', '28.75', '1.15', '6'], 
  ['50kg', '50', '1.0', '5'], 
  ['100kg', '100', '1.0', '3'], 
  ['250kg', '250', '1.0', '5'], 
  ['500kg', '500', '1.0', '5'], 
  ['1liter', '1000', '1.0', '5']];

let labels = ["Weight","Price","Price Per","Amount"];

let values = rows.map((row, idx) => {
  let d = {id: idx};
  row.forEach((c, i) => d[labels[i]] = c);
  return d;
});

console.log(values)

let columns = labels.map(l => ({field: l, width: 150}));

console.log(columns);
BRICK MANE
  • 765
  • 1
  • 5
  • 12

2 Answers2

2

In Python, you can create a dict from the corresponding elements of two lists with dict(zip(keys, values)).

values = [dict(zip(labels, row), id=idx) for idx, row in enumerate(rows)]
columns = [{'field': l, 'width': 150} for l in labels]
Ry-
  • 218,210
  • 55
  • 464
  • 476
0

maybe this is the best i can do for you

rows = [['10kg', '12.5', '1.25', '8'], 
  ['25kg', '28.75', '1.15', '6'], 
  ['50kg', '50', '1.0', '5'], 
  ['100kg', '100', '1.0', '3'], 
  ['250kg', '250', '1.0', '5'], 
  ['500kg', '500', '1.0', '5'], 
  ['1liter', '1000', '1.0', '5']]

labels = ["Weight","Price","Price Per","Amount"]

values = []
for y,i in enumerate(rows):
    a = {}
    a["id"] = y
    for index,x in enumerate(i):
        a[labels[index]] = x
    values.append(a)
    
print(values)

columns = [{"fields": i, "width":150} for i in labels]
print(columns)