Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何编写一个函数来返回Python中的词典列表?_Python - Fatal编程技术网

如何编写一个函数来返回Python中的词典列表?

如何编写一个函数来返回Python中的词典列表?,python,Python,编写一个函数,返回字典列表,其中 字典有三个键产品,品牌,和成本。这个 函数要求用户输入键的值,直到用户 输入退出。例如,如果用户输入以下值 Enter Product: Milk Enter Brand: Anchor Enter Cost: 4.90 Enter Product: Bread Enter Brand: Vogel Enter Cost: 3.80 Enter Product: quit 问了同样的问题后,我得出以下结论: 我不知道这是不是

编写一个函数,返回字典列表,其中 字典有三个键
产品
品牌
,和
成本
。这个 函数要求用户输入键的值,直到用户 输入退出。例如,如果用户输入以下值

 Enter Product: Milk 
 Enter Brand: Anchor  
 Enter Cost: 4.90 

 Enter Product: Bread  
 Enter Brand: Vogel  
 Enter Cost: 3.80 

 Enter Product: quit
问了同样的问题后,我得出以下结论:

我不知道这是不是正确的一步

def run():
    i = True
    dic_keys = ['Milk', 'Brand', 'Cost']
    products = []
    product = {}

    while i:
        for key in dic_keys:
            name_dict = input("Enter Product: ")
        if i != "quit":

我认为这是正确的方向,但正如评论所指出的,您必须更清楚地了解代码应该如何工作。
一种可能的方法是:

def run():
    dic_keys = ['Product', 'Brand', 'Cost']
    products = []

    while True:
        # get an emtpy product dict for every new product
        product = {}

        # get user input for every key (product, brand, cost)
        for key in dic_keys:
            # get input
            val = input(f"Enter {key}: ")

            # if the input is "stop": return results ("quit" is already a python keyword)
            if val == "stop":
                return products

            # add user input to corresponding key (eg. val: Bread, key: Product)
            product[key] = val

        # after we went through all the keys the product dict is finished, so it gets appended to teh products list
        products.append(product)


myProducts = run()
print(myProducts)

我认为这是正确的方向,但正如评论所指出的,您必须更清楚地了解代码应该如何工作。
一种可能的方法是:

def run():
    dic_keys = ['Product', 'Brand', 'Cost']
    products = []

    while True:
        # get an emtpy product dict for every new product
        product = {}

        # get user input for every key (product, brand, cost)
        for key in dic_keys:
            # get input
            val = input(f"Enter {key}: ")

            # if the input is "stop": return results ("quit" is already a python keyword)
            if val == "stop":
                return products

            # add user input to corresponding key (eg. val: Bread, key: Product)
            product[key] = val

        # after we went through all the keys the product dict is finished, so it gets appended to teh products list
        products.append(product)


myProducts = run()
print(myProducts)

我创建了你想要的函数。让我先和你分享我的代码,然后我会解释它

#BLL
def get(产品、品牌、成本):…8
d1={“产品”:产品,“品牌”:品牌,“成本”:成本}..9
列表。附加(d1)…10
打印(d1)…11
打印(列表)…12
#PL
列表=[]…1
而(1):…2
产品=输入(“输入产品”).strip().lower().title()…3
如果(产品==“退出”):…4
打破
品牌=输入(“输入品牌”).strip().lower().title()…5
成本=整数(输入(“输入成本”)…6
获取(产品、品牌、成本)…7
让我们从
#PL
(表示层)下编写的代码块开始。 在第一行中,我创建了一个空列表,它将所有字典存储为一个列表。 在第二行中,我使用了
while(1)
,这样代码将一次又一次地运行,需要用户输入。 在第3行、第5行和第6行中,我只要求用户提供所需的输入。在这里,我使用了
strip().lower().title()
以固定字体存储输入,而不管用户如何提供输入。 在第4行中,我使用了一个
if
语句,这样一旦用户输入
“Quit”
,程序就会终止。 在第7行中,我最终调用了函数

现在,让我们看看在
#BLL
层中编写的代码-调用函数时函数将如何工作。 在第8行,我刚刚调用了函数
get
,并传递了三个键(
Product
Brand
Cost
)。 在第9行中,我将用户提供的输入存储在字典中。 在第10行,我使用
append
将整个字典添加到列表中-记住,我在第1行创建了一个空列表。 在第11行和第12行,我只是将字典和列表返回给用户


我创建了您想要的确切函数。让我先和你分享我的代码,然后我会解释它

#BLL
def get(产品、品牌、成本):…8
d1={“产品”:产品,“品牌”:品牌,“成本”:成本}..9
列表。附加(d1)…10
打印(d1)…11
打印(列表)…12
#PL
列表=[]…1
而(1):…2
产品=输入(“输入产品”).strip().lower().title()…3
如果(产品==“退出”):…4
打破
品牌=输入(“输入品牌”).strip().lower().title()…5
成本=整数(输入(“输入成本”)…6
获取(产品、品牌、成本)…7
让我们从
#PL
(表示层)下编写的代码块开始。 在第一行中,我创建了一个空列表,它将所有字典存储为一个列表。 在第二行中,我使用了
while(1)
,这样代码将一次又一次地运行,需要用户输入。 在第3行、第5行和第6行中,我只要求用户提供所需的输入。在这里,我使用了
strip().lower().title()
以固定字体存储输入,而不管用户如何提供输入。 在第4行中,我使用了一个
if
语句,这样一旦用户输入
“Quit”
,程序就会终止。 在第7行中,我最终调用了函数

现在,让我们看看在
#BLL
层中编写的代码-调用函数时函数将如何工作。 在第8行,我刚刚调用了函数
get
,并传递了三个键(
Product
Brand
Cost
)。 在第9行中,我将用户提供的输入存储在字典中。 在第10行,我使用
append
将整个字典添加到列表中-记住,我在第1行创建了一个空列表。 在第11行和第12行,我只是将字典和列表返回给用户


如果您想添加其他密钥,那么您的代码是可以维护的,但它需要一些修复

试试这个。它只包含一个循环

list_= []                                      
d = {}                                         

i = input("Enter Product: ")              

while(i != "quit"):                            
    d["product"] = i                           
    d["Brand"] = input("Enter Brand: ")   
    d["Cost"] = int(input("Enter Cost: "))

    list_.append(d)                            
    i = input("Enter Product: ")          

print(list_)                                   

如果您想添加另一个键,那么您的代码是可以维护的,但它需要一些修复

试试这个。它只包含一个循环

list_= []                                      
d = {}                                         

i = input("Enter Product: ")              

while(i != "quit"):                            
    d["product"] = i                           
    d["Brand"] = input("Enter Brand: ")   
    d["Cost"] = int(input("Enter Cost: "))

    list_.append(d)                            
    i = input("Enter Product: ")          

print(list_)                                   

如果您不必对输入进行消毒

dic_keys = ['Product', 'Brand', 'Cost']

dic = dict(zip(dic_keys, [input(f'Enter {key}') for key in dic_keys]))
产出

Enter Product     Milk
Enter Brand       CowTeat
Enter Cost        6
{'Product': 'Milk', 'Brand': 'CowTeat', 'Cost': '6'}
所以如果你想要一个字典列表

account = []
while True:
    try:
        account.append(dict(zip(dic_keys, [input(f'Enter {key}') for key in dic_keys])))
    except KeyboardInterrupt:
        break

完成输入后按Ctrl-C键。

如果不必对输入进行消毒

dic_keys = ['Product', 'Brand', 'Cost']

dic = dict(zip(dic_keys, [input(f'Enter {key}') for key in dic_keys]))
产出

Enter Product     Milk
Enter Brand       CowTeat
Enter Cost        6
{'Product': 'Milk', 'Brand': 'CowTeat', 'Cost': '6'}
所以如果你想要一个字典列表

account = []
while True:
    try:
        account.append(dict(zip(dic_keys, [input(f'Enter {key}') for key in dic_keys])))
    except KeyboardInterrupt:
        break

完成输入后按Ctrl-C。

为什么“Milk”硬编码?你的意思可能是“产品”,在这里