Answer the question
In order to leave comments, you need to log in
How to read a file into a dictionary in python?
Hello! How to read a file in this format:
Pizza: 01
Coffee: 02
And write it into a dictionary, where the value before the colon is the key, after the colon is the value?
Answer the question
In order to leave comments, you need to log in
with open('data.txt') as file: #Читаем файл
lines = file.read().splitlines() # read().splitlines() - чтобы небыло пустых строк
dic = {} # Создаем пустой словарь
for line in lines: # Проходимся по каждой строчке
key,value = line.split(': ') # Разделяем каждую строку по двоеточии(в key будет - пицца, в value - 01)
dic.update({key:value}) # Добавляем в словарь
print(dic) # Вывод словаря на консоль
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question