2016-12-07 139 views
-1

所以,我有一个功能,应该要求用户输入一个大陆的名称,然后函数应该通过Dictionary [“values”]来查找该大陆,然后搜索通过字典中的所有国家[“关键字”]打印列表中所有大陆国家。打印与字典值相关的关键字

词典[“值”] =大洲列表 词典[“关键字”] =国家

的名单到目前为止,我有:

def filterCountriesByContinent(self): 
    continentinp = input(str("Please enter a continent: ")) #user input 
    if continentinp in self.Dictionary["values"]: #check if input in Dictionary.values 
     return print(self.Dictionary["keywords"]) #if in Dictionary.values, print off associated countries 
    else: 
     return print("That country is not in the Dictionary") 

现在它只是打印关闭Dictionary [“关键字”]中的所有国家/地区列表,包括不在输入大陆的国家/地区列表。

+0

难道你没有大陆映射到国家吗? –

+0

'print(self.Dictionary [“keywords”])'总是会打印同样的东西。它不应该与“continentinp”有关吗? –

+0

在前面的函数中,我们接受一个txt文件的输入,将数据拆分为多个部分,并将这些部分与Dictionary [“values”]和Dictionary [“keywords”]关联起来。我试图弄清楚如何将它们联系起来,以便创建可正常工作的不同打印部分。 – MezyMinzy

回答

1

首先需要大陆及其国家的字典。它应该看起来像这样。

{ 
    "North America": [ 
    "United States of America", 
    "Canada", 
    "Cuba", 
    "Mexico" 
    ], 
    "South America": [ 
    "Brazil", 
    "Argintina" 
    ], 
    "Europe": [ 
    "United Kingdom", 
    "Germany" 
    ], 
    "Africa": [ 
    "Egypt" 
    ] 
} 

然后Python代码是这样的。

dict_of_cont = # here is your dictionary 
continent = raw_input("Enter the continent you wish to list the countries of: ") 
for cont in dict_of_cont[continent.lower()]: # loop through the countries. 
    print(cont + " is in " + continent.lower()) 

但是请注意,您必须阐明国家有权得到任何结果。

+0

你碰巧知道可能需要投入,如中国,亚洲 功能美利坚合众国,北美 巴西,南美 日本,亚洲 加拿大,北美 印度尼西亚,亚洲 尼日利亚,非洲 墨西哥,北美 埃及,非洲 法国,欧洲 意大利,欧洲 南非,非洲 韩国,亚洲 南美洲哥伦比亚 和同大陆所有的人聚集到像一个你表现出一本字典?请注意,提供的国家和洲的列表是一个txt文件,每个国家/地区都设置在不同的行上。 – MezyMinzy

+0

你可以尝试使用CSV,[链接这里。](https://docs.python.org/2/library/csv.html)然后用换行符去除文件('str.strip(“\ n”)) '),然后为每个值附加到大陆的字典。如果您希望我在答案中提供示例,请编辑您的问题。 –