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

时间:2018-10-05 02:59:26

标签: python python-3.x list dictionary

是否可以使用用户输入从字典中的列表创建列表/字典?

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] 

到目前为止,我已经能够在字典中创建列表,但是无法从列表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()

1 个答案:

答案 0 :(得分:1)

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

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

我想如果需要,您可以将其纳入课堂。