繁体   English   中英

如何在Python的字典中存储文件?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM