How do I combine three separate list into one single dictionary?
Currently I have three operator inputs, where each input is split into a list.
item_input = input("Enter products seperated by space")
price_input = input("Enter price seperated by space")
stock_input = input("Enter stock seperated by space")
items = item_input.split()
price = price_input.split()
stock = stock_input.split()
I assume my first step would be to combine the price_input and stock_input into one dictionary first, and then nest them into the products_input.
I’ve tried using the fromkey method to make the price_input in its own dictionary to start with but the keys and values are in the opposite positions that I want
Example code:
price = [1,2,3]
price_dict = dict.fromkeys (price, "price")
#Output = {1: 'price', 2: 'price', 3: 'price'}
#Inteded output = {"price": 1, "price": 2, "price": 3}
This is the intended final output that I need.
products = {
"apple": {"price": 3.5, "stock": 134},
"banana": {"price": 6.82, "stock": 52},
"cake": {"price": 23, "stock": 5}
}
>Solution :
You can zip item, price and stock together and then just use a dictionary comprehension:
items = input("Items: ").split()
prices = map(float, input("Prices: ").split())
stocks = map(int, input("Stocks: ").split())
products = {
item: {"price": price, "stock": stock}
for item, price, stock in zip(items, prices, stocks)
}
However, it might be better if the user could enter items one by one instead of having to add all at once so you could use a loop for that, the user inputs values separated by comma and to exit just doesn’t type anything, simply pressers enter key.
products = {}
new_product = input("Item, price, stock: ")
while new_product:
item, price, stock = new_product.split(",")
products[item.strip()] = {"price": float(price), "stock": int(stock)}
new_product = input("Item, price, stock: ")