在dictonary循环的python函数

时间:2018-04-26 03:33:04

标签: python function dictionary for-loop

我试图从字典中的特定键中检索所有项目。代码有效,但我在函数None的输出中继续收到general_info语句。另一个函数specific_info正常工作。有什么建议吗?非常感谢。

countries = {
"canada": {
    'name': "Canada",
    'location': "North America",
    'currency': "Canadian Dollar",
    'capital city': "Ottawa",
    'population': "32.268.240",
    'area': "9.970.610 km2"
},
"brazil": {
    'name': "Brazil",
    'location': "South America",
    'currency': "Brazilian Real",
    'capital city': "Brasilia",
    'population': "186.404.900",
    'area': "8.514.877 km2"
},
"ukraine": {
    'name': "Ukraine",
    'location': "Europe",
    'currency': "Ukrainian Hryvnia",
    'capital city': "Kyiv",
    'population': "46.480.700",
    'area': "603.700 km2"
},
"haiti": {
    'name': "Haiti",
    'location': "North America",
    'currency': "Haitian Gourde",
    'capital city': "Port-au-Prince",
    'population': "8.527.777",
    'area': "27.750 km2"
},
"albania": {
    'name': "Albania",
    'location': "Europe",
    'currency': "Albanian Lek",
    'capital city': "Tirana",
    'population': "3.129.678",
    'area': "28.748 km2"
},
"india": {
    'name': "India",
    'location': "Asia",
    'currency': "Indian Rupee",
    'capital city': "New Delhi",
    'population': "1.103.371.000",
    'area': "3.287.263 km2"


 }
}

def general_info(c_name):
    for key, val in countries[c_name].items():
        info = print(c_name.title() + " " + key + " is " + val)
    return info

def specific_info(c_name, info):
    if c_name in countries and info in countries[c_name].keys():
        return (info.title() + " from " + c_name.title() + " is " + countries[c_name][info])


ask_country = input("Country name: ")

ask_info = input("Information requested: ")

c_name = ask_country.lower()

info = ask_info.lower()

print(general_info(c_name))
print()
print(specific_info(c_name, info))

2 个答案:

答案 0 :(得分:1)

您将返回print语句的返回值,该值始终为None。只需删除打印件即可。

答案 1 :(得分:1)

以下代码中存在多个问题:

def general_info(c_name):
    for key, val in countries[c_name].items():
        # overwrites info in every iteration
        # you are saving return value of print function
        info = print(c_name.title() + " " + key + " is " + val)  
    return info  # return only last iteration "info"

def specific_info(c_name, info):
    if c_name in countries and info in countries[c_name].keys(): # you can simply write info in countries[c_name]. No need of ".keys()" method
        return (info.title() + " from " + c_name.title() + " is " + countries[c_name][info])

要返回一般信息,您应该执行以下操作:

def general_info(c_name):
    general_info = []
    for key, val in countries[c_name].items():
        info = (c_name.title() + " " + key + " is " + val)
        general_info.append(info )
    return general_info

另外,要格式化字符串,您应该尝试使用format函数。我会重写信息:

info = "{country}: {key} is {val}".format(country=c_name.title(), key=key, val=val)

这使您的代码更易读,也更容易编写。