Skip to content Skip to sidebar Skip to footer

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 Mars

Solution 1:

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 = []                                                                                                                         
withopen('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}

Post a Comment for "How Do I Create A Dictionary From A .txt File With Whitespace In Python"