I have two objects, a variable (username), and a list (products) of products and costs
JavaScript
x
6
1
usernames = ['Dave','mary','John']
2
3
products (nested list)
4
[['pr1', '40.0', 'pr2', '50.0', 'pr4', '70.0'],['pr2', '35.5', 'pr3', '36.0', 'pr4', '65.5'],
5
['pr1', '23.0', 'pr2', '45,4']]
6
All prices are unique to each customer. Similarly, the product set is also unique to each customer, so I cant say take a specific index such as products[0] and it would always be ‘pr1’.
I’ve zipped the two objects together:
JavaScript
1
5
1
for x,y in zip(usernames,products):
2
print(x,y)
3
>>>> dave, ['pr1', '40.0', 'pr2', '50.0', 'pr4', '70.0']
4
5
This gets me part way there, but I cant figure out how to append in the missing Products and ‘N/A’ for each username.
My end goal is a view that looks like this, dropping the ‘pr’ product keys so that I can use this to visualise the data:
JavaScript
1
6
1
dave ['40.0', '50.0', 'N/A', '70.0']
2
Mary ['N/A', '35.5', '36.0, '65.5']
3
John ['23.0, '45.4', 'N/A', 'N/A']
4
5
6
Please help Python masters, I’ve been trying everything for hours and I’m all out of ideas..
Advertisement
Answer
you can try dict
JavaScript
1
16
16
1
usernames = ['Dave','mary','John']
2
3
products = [['pr1', '40.0', 'pr2', '50.0', 'pr4', '70.0'],['pr2', '35.5', 'pr3', '36.0', 'pr4', '65.5'],['pr1', '23.0', 'pr2', '45,4']]
4
def get_products(data):
5
template = {f'pr{i}': 'N/A' for i in range(1,5)}
6
template.update(**data)
7
return list(template.values())
8
9
d = [dict([p[i:i+2] for i in range(0,len(p),2)]) for p in products]
10
result = [get_products(i) for i in d]
11
print(result)
12
13
# [['40.0', '50.0', 'N/A', '70.0'],
14
# ['N/A', '35.5', '36.0', '65.5'],
15
# ['23.0', '45,4', 'N/A', 'N/A']]
16