Skip to content
Advertisement

How to iterate over nested list to input missing values

I have two objects, a variable (username), and a list (products) of products and costs

usernames = ['Dave','mary','John']

products (nested list)
[['pr1', '40.0', 'pr2', '50.0', 'pr4', '70.0'],['pr2', '35.5', 'pr3', '36.0', 'pr4', '65.5'],
['pr1', '23.0', 'pr2', '45,4']]

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:

for x,y in zip(usernames,products):
            print(x,y)
>>>> dave, ['pr1', '40.0', 'pr2', '50.0', 'pr4', '70.0']

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:

dave ['40.0', '50.0', 'N/A', '70.0']
Mary ['N/A', '35.5', '36.0, '65.5']
John ['23.0, '45.4', 'N/A', 'N/A']


Please help Python masters, I’ve been trying everything for hours and I’m all out of ideas..

Advertisement

Answer

you can try dict

usernames = ['Dave','mary','John']

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']]
def get_products(data):
    template = {f'pr{i}': 'N/A' for i in range(1,5)}
    template.update(**data)
    return list(template.values())

d = [dict([p[i:i+2] for i in range(0,len(p),2)]) for p in products]
result = [get_products(i) for i in d]
print(result)

# [['40.0', '50.0', 'N/A', '70.0'], 
# ['N/A', '35.5', '36.0', '65.5'], 
# ['23.0', '45,4', 'N/A', 'N/A']]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement