Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a nested dictionary from multiple list?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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: ")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading