为什么我的函数不会在字典中附加键值?

时间:2013-09-18 02:21:19

标签: python dictionary

所以我定义了这个函数来询问你一个国家的名字,然后给你一个有趣的事实。它应该问您是否要将您询问的国家/地区添加到字典中(如果它还不知道它)。我认为代码很好。但是在它询问你之后,它并没有真正将新的国家事实添加到词典中:/有人可以确定问题吗?

def countries():
    param = input("please enter the country you'd like a fun fact about")
    listofcountries = {"Kuwait": "has 10% of the world's oil reserves.", "UAE": "has the world's highest free-standing structrure, Burj Khalifa.", "Qatar": "is hosting the FIFA 2022 world cup.", "Saudi Arabia": "is the largest GCC country.", "Bahrain": "held the Dilmun civilization, one of the world's oldest civilizations.", "Oman": "is known for its beautiful green mountains."}
    if (param in listofcountries):
        print ("I know something about", param)
        print (param, listofcountries[param])
    else:
        print ("I don't know anything about", param)
        add_yesorno = input("Would you like to add something to the list? (yes or no)")
        if add_yesorno == 'yes':
            country_name = input("What's its name again?")
            add_yes = input("please finish this sentence. This country...")
            print ("Thanks a lot for contributing to the list!")
            listofcountries[country_name] = add_yes
        else:
            print ("Thanks then! See you later.")

3 个答案:

答案 0 :(得分:1)

listofcountries是一个局部变量,因此每次调用该函数时都会重置。如果您希望它在调用之间保持其值,则需要将其设置为全局(或其他更高的范围)。

listofcountries = {"Kuwait": "has 10% of the world's oil reserves.", "UAE": "has the world's highest free-standing structrure, Burj Khalifa.", "Qatar": "is hosting the FIFA 2022 world cup.", "Saudi Arabia": "is the largest GCC country.", "Bahrain": "held the Dilmun civilization, one of the world's oldest civilizations.", "Oman": "is known for its beautiful green mountains."}

def countries():
    param = input("please enter the country you'd like a fun fact about")
    if (param in listofcountries):
        print ("I know something about", param)
        print (param, listofcountries[param])
    else:
        print ("I don't know anything about", param)
        add_yesorno = input("Would you like to add something to the list? (yes or no)")
        if add_yesorno == 'yes':
            country_name = input("What's its name again?")
            add_yes = input("please finish this sentence. This country...")
            print ("Thanks a lot for contributing to the list!")
            listofcountries[country_name] = add_yes
        else:
            print ("Thanks then! See you later.")

另请注意,我已将input的所有实例更改为raw_input。你想读一个字符串,所以你绝对想要raw_inputinput函数实际上会评估输入,将其转换为符号或原始文字值。

根据下面的评论,我已经恢复到input,因为显然这是Python 3中的正确功能。

答案 1 :(得分:0)

好吧,listofcountries是函数countries()中的局部变量。当函数返回时,你的字典就会消失!连同所有其他局部变量(例如paramadd_yes)。

最好在函数外定义listofcountries ,作为模块全局。然后listofcountries将在countries的调用中保留其值。

更高级的是创建一个类,并将dict存储为类的属性。但是,除此之外,将其作为全球模块可以快速解决您的问题。

答案 2 :(得分:0)

listofcountries是本地的,每次都会被重置。您可以使用具有默认值的参数来保持跨调用,这允许您在不污染全局名称空间的情况下缓存任何结果:

def countries(listofcountries = {}):
    defaultlist = {"Kuwait": "has 10% of the world's oil reserves.", "UAE": "has the world's highest free-standing structrure, Burj Khalifa.", "Qatar": "is hosting the FIFA 2022 world cup.", "Saudi Arabia": "is the largest GCC country.", "Bahrain": "held the Dilmun civilization, one of the world's oldest civilizations.", "Oman": "is known for its beautiful green mountains."} 
    if not listofcountries:
        listofcountries.update(defaultlist)
    ...