How do I make a Python dictionary from .txt file?

Viewed 67

I new at programming and need some help. I am trying to create a Python dictionary from a .txt file, but I am not sure how go about it. The format of the file is with hundreds of lines:

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

Ideally I would like to have it the dictionary look like this:

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

This is what I have been trying to work with:

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

Please help

2 Answers

You could do it like this, iterating on the lines of the file and using next() to get the description on the next line in the same loop:

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!'}

Code

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])}

Test

import pprint
pprint.pprint(dict1)

Test File list_test.txt

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

Output

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