读取文本文件并存储到字典中

时间:2017-02-08 18:26:13

标签: python

我试图找出将文件内容存储到特定密钥中的多个值。

期望的输出:

{'city1':[Island-1,Island-3],'city2':[Island-2,Island-4]}

的data.txt

city1-south:"London"
city1-south:"Paris"
city1-north:"Amsterdam"
city1-north:"Island-1"
city2-south:"Island-2"
city1-east:"Island-3"
city2-west:"Island-4"


def readFile(data_file):
    data = open(data_file,"r")
    d = {}
    for line in data:
        if 'Island' in line:
            city,loc = line.rstrip("\n").split(":",1)
            d[city] = loc
    print (d)
    data.close()

data_file = "data.txt"
readFile(data_file)

当前输出:

{'city2-south': '"Island-2"', 'city2-west': '"Island-4"', 'city1-east': '"Island-3"', 'city1-north': '"Island-1"'}

1 个答案:

答案 0 :(得分:0)

我现在无法运行您的代码,因为未定义with open("data.txt") as data: d = {'city1': [], 'city2': []} for line in data: if 'Island' in line: city,loc = line.rstrip("\n").split(":",1) for key in d.keys(): if key in city: d[key].append(loc[1:-1]) print(d) 。我做了一些修改,以便您的代码可以运行。

{'city1': ['Island-1', 'Island-3'], 'city2': ['Island-2', 'Island-4']}

结果:

{{1}}

现在 Island-1 等不能在字典中输出为字符串,否则python会将它们视为变量。