简体   繁体   English

Python 3:如何使用用户输入从字典中列表中的值创建列表(或字典)?

[英]Python 3: How to create a list (or dictionary) from a value in a list inside a dictionary using user's input?

Is it possible if I create a list/dictionary from a list inside a dictionary using user's input? 如果我可以使用用户输入从字典中的列表创建列表/字典,是否可以?

E.g.
in the dictionary: {'fruits', 'veggies', 'drinks'}
every key has list:  fruits = ['apple','manggo']
every value has a list (or maybe dict): apple = ['stock':30, 'amount':10] 

So far I was able to create a list inside a dictionary but I can't create a new list from every value in the list apple = ['stock':30] . 到目前为止,我已经能够在字典中创建列表,但是无法从列表apple = ['stock':30]中的每个值创建新列表。

My code 我的密码

class Inventory:


    def __init__(self):

        self.dict_inv = dict()
        self.count_inv = int(input("Enter the number of inventories: "))


        for count in range(self.count_inv):

            name_inv = str(input("Enter Inventory #%d: " % (count+1)))
            self.dict_inv[name_inv] = count
            self.dict_inv[name_inv] = []


        for name_inv in self.dict_inv:

            max_item = int(input("How many items in {} " .format(name_inv)))

            for count in range(max_item):

                name_item = str(input("Enter item #%d: " % (count+1)))
                self.dict_inv[name_inv].append(name_item)
                self.dict_inv[name_inv[name_item]] = [] # <-- ERROR

        # PRINTS EVERYTHING 
        for key in self.dict_inv.keys():

            if type(self.dict_inv[key]) is list:
                print("{} is a list" .format(key))
                print("items in {} are {}" .format(key, self.dict_inv[key]))


Inventory()

Not sure you to need to create a class for this. 不确定您是否需要为此创建一个类。 Will this accomplish what you are trying to do? 这样可以完成您想要做的事情吗?

# define a generator that ask the user to enter things until they quit.
def ask(thing):
    user_input = 'x'
    while user_input != 'quit':
        user_input = input("Enter %s or 'quit' to stop: " % (thing))
        if user_input != 'quit':
           yield(user_input)


# use list comprehension to create inventory
inventory = [{c: [ {i: int(input("Enter stock: "))} for i in ask("item")]} for c in ask("category")]

# voila!
print( inventory )

Here's what happens when the above code executes: 执行以上代码后,将发生以下情况:

$ python3 inventory.py
Enter category or 'quit' to stop: fruit
Enter item or 'quit' to stop: apples
Enter stock: 45
Enter item or 'quit' to stop: bananas
Enter stock: 23
Enter item or 'quit' to stop: berries
Enter stock: 47
Enter item or 'quit' to stop: quit
Enter category or 'quit' to stop: cars
Enter item or 'quit' to stop: fords
Enter stock: 4
Enter item or 'quit' to stop: toyotas
Enter stock: 7
Enter item or 'quit' to stop: quit
Enter category or 'quit' to stop: quit
[{'fruit': [{'apples': 45}, {'bananas': 23}, {'berries': 47}]}, {'cars': [{'fords': 4}, {'toyotas': 7}]}]

I guess you can get that into a class if you want. 我想如果需要,您可以将其纳入课堂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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