0
Я пытаюсь найти содержимое файла в несколько значений в конкретном ключе.Прочитать текстовый файл и сохранить в словаре
Желаемый результат:
{'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"'}
Спасибо за ответ. Он работает отлично. – Balen