首页 > 解决方案 > Python 3:如何使用用户输入从字典内列表中的值创建列表(或字典)?

问题描述

如果我使用用户输入从字典中的列表创建列表/字典,是否有可能?

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] 

到目前为止,我能够在字典中创建一个列表,但我无法从 list 中的每个值创建一个新列表apple = ['stock':30]

我的代码

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()

标签: pythonpython-3.xlistdictionary

解决方案


不确定您是否需要为此创建一个类。这会完成你想要做的事情吗?

# 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 )

以下是上述代码执行时发生的情况:

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

我想如果你愿意的话,你可以把它带进课堂。


推荐阅读