[英]How do I store a file in a dictionary in Python?
我正在嘗試將一個包含國名及其人均收入的文本文件存儲到詞典中,然后輸出該詞典。
到目前為止,我擁有的代碼將文件存儲在字典中並成功輸出,除非我不弄清楚如何在不從值中刪除美元符號的情況下做到這一點。
到目前為止,這是我的代碼:
def extractData(infile) :
record = {}
line = infile.readline()
if line != "" :
fields = line.split('$')
record["country"] = fields[0]
record["percap"] = int(fields[1].replace(',', ""))
return record
infile = open("percapita.txt", "r")
record = extractData(infile)
while len(record) > 0:
print("%-20s %10d" % (record["country"], record["percap"]))
record = extractData(infile)
我怎樣才能解決這個問題?
看來您正在使用$來分割行。 這意味着它不再是您產品線的一部分。 我建議改用空白標識符之一(適合您的文本文件)。
def extractData(infile) :
record = {}
line = infile.readline()
if line != "" :
fields = line.split(' ') # or '\t'
record["country"] = fields[0]
record["percap"] = int(fields[1].replace(',', ""))
return record
infile = open("percapita.txt", "r")
record = extractData(infile)
while len(record) > 0:
print("%-20s %10d" % (record["country"], record["percap"]))
record = extractData(infile)
您並未將鍵與所有情況下的值相關聯,在每次迭代中都會刪除字典,因此,當您要訪問一個值時,只有最后一個
我推薦這個
def extractData(infile) :
record = {}
while True:
line = infile.readline()
if line == "" :
break
fields = line.split('$')
record[fields[0]] = int(fields[1].replace(',', ""))
return record
infile = open("percapita.txt", "r")
record = extractData(infile)
for k in record.keys():
print(k , " $" , record[k])
除了@Stephopolis的答案,我認為您沒有使用字典來達到目的。 您的鍵值應為國家/地區名稱。 例如,您應該添加如下值:
record["IsleofMan"] = "$83100"
當您想獲取某個國家的人均價值時,只需從詞典中查詢它即可。
print(record["IsleofMan"])
將給出的輸出
$83100
要獲取用戶輸入,您可以使用:
country_query = input()
所以當我們把它們放在一起
def extractData(infile) :
record = {}
line = infile.readline()
if line != "" :
fields = line.split(' ') # or '\t'
record[fields[0]] = fields[1]
return record
infile = open("percapita.txt", "r")
record = extractData(infile)
country_query = input()
print(record["IsleofMan"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.