简体   繁体   English

如何将多个输入循环到字典文件 Wirth Python?

[英]How do I loop several inputs into a dictionary file Wirth Python?

My goal is to take two user inputs on a loop, save them in a dictionary, and when the user ends the loop, to have the save the dictionary.我的目标是在一个循环中获取两个用户输入,将它们保存在字典中,当用户结束循环时,保存字典。

# ------ Global Variables -------

user_cont = True

# ------- Functions -------

def get_Product():
    while user_cont:

        # get product code
        get_ProductCode()

        # get product number
        get_ProductNum()

        # save to dict
        create_ProductDict()

        # ask to continue
        user_continue()

        # save dict to file

def get_ProductCode(): works def get_ProductCode():有效

def get_ProductNum(): works def get_ProductNum():有效

def user_continue(): works but now is not getting prompted def user_continue():有效,但现在没有得到提示

What I'm currently trying to fix:我目前正在尝试解决的问题:

# save to dictionary
def create_ProductDict(): 
   product_Dict = {}
   productCode = get_ProductCode()
   productNum = get_ProductNum()
   print(product_Dict)

By my understanding on each loop, it should be receiving the returned productCode and productNum, and storing them?根据我对每个循环的理解,它应该接收返回的 productCode 和 productNum 并存储它们? But now it won't ask the user to continue and end the loop so I can view the dictionary before I attempt to have the user save it.但现在它不会要求用户继续并结束循环,因此我可以在尝试让用户保存字典之前查看字典。

In addition, I need to have the user choose a filename for the data.此外,我需要让用户为数据选择一个文件名。

As always, help is much appreciated!一如既往,非常感谢您的帮助!

There are two problems here.这里有两个问题。 First issue is that your dictionary is being destroyed once the create_ProductDict() function ends, since the dictionary is created within the scope of the function.第一个问题是,一旦 create_ProductDict() function 结束,您的字典就会被销毁,因为字典是在 function 的 scope 中创建的。

One way to get around this would be to declare the dictionary in the global scope as a global variable.解决此问题的一种方法是将全局 scope 中的字典声明为全局变量。 This way, the dictionary will persist as more items are added to it.这样,随着更多项目添加到字典中,字典将持续存在。

Next, your input variables currently aren't being used and the dictionary isn't being added to.接下来,您的输入变量当前没有被使用并且字典没有被添加到。 The syntax for this is as follows:其语法如下:

productDict[productCode] = productNumber

So assuming that your input functions are equivalent to python's input() function, a solution that solves both of these issues would look something like this:因此,假设您的输入函数等效于 python 的 input() function,解决这两个问题的解决方案将如下所示:

products = {}

def create_product_dict():
    code = input("Enter Code: ")
    num = input("Enter Number: ")
    products[code] = num 

create_product_dict()
create_product_dict()

print(products)

The output of this would be: output 将是:

Enter Code: 123
Enter Number: 456
Enter Code: abc
Enter Number: 596
{'123': '456', 'abc': '596'}

Hope this is helpful:)希望这会有所帮助:)

Try this:尝试这个:

def get_Product():
    user_cont = True
    while user_cont:
        get_ProductCode()
        get_ProductNum()
        create_ProductDict()
        user_cont = user_continue()

def user_continue():
    ip = input('Enter Yes to Continue: ').lower()
    return True if ip == 'yes' else False

Here is my finished main function after everything above pointed me in the direction I needed, but was not able to answer my questions entirely.这是我完成的主要 function 在上面的一切都指向我需要的方向之后,但无法完全回答我的问题。 My key finding was updating the dictionary before I asked to continue, and then adding the saving of the dictionary at the end.我的主要发现是在我要求继续之前更新字典,然后在最后添加字典的保存。 (The additional functions not included here as did not pertain to question/solution. Thank you! (此处未包含的附加功能与问题/解决方案无关。谢谢!

    user_cont = True
    while user_cont:

        # get product code
        productCode = get_ProductCode()

        # get product number
        productNum = get_ProductNum()

        # print(productCode, productNum)

        # save to dict
        products[productCode] = productNum

        # debug to ensure dictionary was saving multi lines
        # print(products)

        # ask to continue
        user_cont = user_continue()

    for productCode, productNum in products.items():
        formproducts = (productCode + ", " + productNum)

        # print test
        # print(formproducts)

    # save dict to file
    FILENAME = input(str("Please enter a file name: "))
    file = open(FILENAME, "w")
    file.write( str(products) )
    file.close()
    print("File saved.")

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

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