[英]How to create a nested dictionary from multiple 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()
我假设我的第一步是先将 price_input和stock_input 组合到一个字典中,然后将它们嵌套到products_input中。
我尝试使用 fromkey 方法在自己的字典中创建price_input ,但键和值位于我想要的相反位置
示例代码:
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}
这是我需要的预期最终 output。
products = {
"apple": {"price": 3.5, "stock": 134},
"banana": {"price": 6.82, "stock": 52},
"cake": {"price": 23, "stock": 5}
}
你可以用字典理解来做到这一点:
answer={x[0]: {"price": x[1], "stock" : x[2]} for x in zip(items, price, stock)}
这类似于列表推导,但返回一个字典。
zip(items, price, stock)
将三个列表变成一个元组列表。 实际上它可能是一个生成器 - 但这里的效果是一样的。 然后它只是迭代这个加入的列表/生成器并构造最终字典的每个条目。
您可以将zip
项目、价格和库存放在一起,然后只需使用字典理解:
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)
}
但是,如果用户可以一个一个地输入项目而不是一次添加所有项目可能会更好,这样您就可以为此使用循环,用户输入以逗号分隔的值并退出只是不输入任何内容,只需按下输入键。
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: ")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.