简体   繁体   中英

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

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}
    }

You could do this with a dictionary comprehension:

answer={x[0]: {"price": x[1], "stock" : x[2]} for x in zip(items, price, stock)}

This is similar to a list comprehension but returns a dictionary.

zip(items, price, stock) turns the three lists into a single list of tuples. Actually it is probably an generator - but here the effect here is the same. Then it just iterate over this joined List/generator and construct each entry of the final dictionary.

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: ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM