简体   繁体   中英

How do I write a function that returns a list of dictionaries in Python?

Write a function that returns a list of dictionaries, where each dictionary has the three keys Product , Brand , and Cost . The function asks the user to input values for the keys until the user inputs quit. For instance, if the user enters the following values

 Enter Product: Milk Enter Brand: Anchor Enter Cost: 4.90 Enter Product: Bread Enter Brand: Vogel Enter Cost: 3.80 Enter Product: quit

Having asked the same question, I come up with this:

I wonder if this is the right step.

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":

I'd say that's the right direction, but as the comments pointed out, you have to get a bit more clear on how your code should work.
A possible way you could go would be:

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)

Your code is OK and maintainable if you would like to add another keys, but it needs some fixes.

Try this. It just include one loop only.

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

I created the exact function you were looking for. Let me share my code with you first, then I will explain it.

# BLL
def get(product,brand,cost):                            ..8
    d1 = {"Product":product,"Brand":brand,"Cost":cost}  ..9
    List.append(d1)                                     ..10
    print(d1)                                           ..11
    print(List)                                         ..12


# PL
List = []                                                        ..1
while(1):                                                        ..2
    product=input("Enter the Product").strip().lower().title()   ..3
    if(product=="Quit"):                                         ..4
        break
    brand = input("Enter the Brand").strip().lower().title()     ..5
    cost = int(input("Enter the cost"))                          ..6
    get(product,brand,cost)                                      ..7 

Let's start from the code block written under # PL (Presentation layer). In the first line, I created an empty list which will be storing all the dictionaries as a list. In the 2nd line, I used while(1) so that the code would run again and again and would require input from the user. In the 3rd, 5th and 6th lines, I just ask the user to give the required inputs. Here, I have used strip().lower().title() to store the input in a fixed font, irrespective how the user provides it. In the 4th line, I used an if statement so that as soon as the user gives "Quit" as input, the program would terminate. In the 7th line, I finally call the function.

Now let's see the code written in # BLL layer - how the function is going to work when it's called. In the 8th line, I just called the function get and passed the three keys( Product , Brand , Cost ). In the 9th line, I stored the inputs given by the user in the dictionary. In the 10th line, I added the whole dictionary into the list using append - remember, I created an empty list in line 1. In the 11th and 12th line, I just return the dictionary and the list to the user.

输出窗口

If you don't have to sanitize the input;

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

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

Output;

Enter Product     Milk
Enter Brand       CowTeat
Enter Cost        6
{'Product': 'Milk', 'Brand': 'CowTeat', 'Cost': '6'}

So if you want a list of dictionaries;

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

Press Ctrl-C when finished with the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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