Skip to content
Advertisement

How do I create a dictionary from a .txt file with whitespace in python

This is the .txt file that I have to work with. I cannot change the file in anyway.

Avignon 48
Bordeaux -6
Brest -45
Caen -4
Calais 18

Dijon 51
Grenoble 57
Limoges 12
Lyon 48
Marseille 53

Montpellier 36
Nantes -16
Nancy 62
Nice 73
Paris 23

Rennes -17
Strasbourg 77
Toulouse 14

I am having an issue turning this file into a dictionary. This is the method that I am currently trying to use.

d = {}
when open("dict.txt") as f:
    for line in f:
        if line.endswith('n'):
            (key, val) = line.split()
            d[key] = int(val)

        elif line.endswith('nn'):
            (key, val) = line.split()
            d[key] = int(val)
    print(d)

The issue is when there is an extra space between the sets of text in the .txt file. When there are no extra spaces, I can create the dictionary without any issues.

Traceback (most recent call last):
  File "C:UsersalexaPycharmProjectspythonProject4Data.py", line 73, in 
  <module>
    (key, val) = line.split()
ValueError: not enough values to unpack (expected 2, got 0)

This is the error that I am getting. How do I fix this issue?

Advertisement

Answer

The issue here is that an empty line will be ‘n’, so you can’t distinguish between an empty line vs other lines given that all lines will end with ‘n’. Here’s my suggestion using list comprehension and a for loop. Probably could do it in a single dict comprehension.

# Read in file
lines = []                                                                                                                         
with open('file.txt', 'r') as f: 
    lines = f.readlines()

# Split out and drop empty rows
strip_list = [line.replace('n','').split(' ') for line in lines if line != 'n']

d = dict()
for strip in strip_list: 
    d[strip[0]] = int(strip[1]) 

Output:

{'Avignon': 48,
 'Bordeaux': -6,
 'Brest': -45,
 'Caen': -4,
 'Calais': 18,
 'Dijon': 51,
 'Grenoble': 57,
 'Limoges': 12,
 'Lyon': 48,
 'Marseille': 53,
 'Montpellier': 36,
 'Nantes': -16,
 'Nancy': 62,
 'Nice': 73,
 'Paris': 23,
 'Rennes': -17,
 'Strasbourg': 77,
 'Toulouse': 14}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement