2016-12-07 63 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」)) '),然後爲每個值附加到大陸的字典。如果您希望我在答案中提供示例,請編輯您的問題。 –