R
R
Roman Roman2020-05-07 23:18:45
Python
Roman Roman, 2020-05-07 23:18:45

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

1 answer(s)
S
Sergey Karbivnichy, 2020-05-07
@Romanvd0412

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) # Вывод словаря на консоль

Dictionary output:
{'Pizza': '01', 'Coffee': '02'}
Added: you can also split like this - "line.split(': ')" - space after the colon, then in the dictionary in the values ​​before the numbers there will be no gap.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question