Как сделать словарь Python из файла .txt? - PullRequest
2 голосов
/ 02 апреля 2020

Я новичок в программировании и мне нужна помощь. Я пытаюсь создать словарь Python из файла .txt, но я не уверен, как это сделать go. Формат файла состоит из сотен строк:

Albariño
Spanish white wine grape that makes crisp, refreshing, and light-bodied wines

В идеале хотелось бы, чтобы словарь выглядел следующим образом:

dictionary1 = {key:value}
dictionary1 = {"Albariño":"Spanish white wine grape that makes crisp, refreshing, and light-bodied wines"}

Это то, что я пытался работать с:

dictionary1 = {}
with open("list_test.txt", 'r') as f:
    for line in f:
        (key, val) = line.splitlines()
        dictionary1[key] = val
print(dictionary1)

Пожалуйста, помогите

Ответы [ 2 ]

1 голос
/ 02 апреля 2020

Вы можете сделать это так, перебирая строки файла и используя next(), чтобы получить описание на следующей строке в том же l oop:

dictionary1 = {}
with open("list_test.txt", 'r') as f:
    for line in f:
        key = line.strip()
        val = next(f).strip()
        dictionary1[key] = val
print(dictionary1)

# {'Albariño': 'Spanish white wine grape that makes crisp, refreshing, and light-bodied wines', 
#  'Some other wine': 'Very enjoyable!'}
0 голосов
/ 02 апреля 2020

Код

with open("list_test.txt", 'r') as f:
  lines = f.read().split('\n')
  dict1 = {x.rstrip():y.rstrip() for x, y in zip(lines[0::2], lines[1::2])}

Тест

import pprint
pprint.pprint(dict1)

Файл теста list_test.txt

lbariño
Spanish white wine grape that makes crisp, refreshing, and light-bodied wines
fred
Italian red wine
Maria
French wine

Выход

{'Maria': 'French wine',
 'fred': 'Italian red wine',
 'lbariño': 'Spanish white wine grape that makes crisp, refreshing, and '
            'light-bodied wines'}
...