Alexander Wills
Alexander Wills

Reputation: 25

How to convert a text file to a dictionary in python?

I have the following text file.

BREST:
Rennes 244

RENNES:
Breast 244
Caen 176
Nantes 107
Paris 348

CAEN:
Calais 120
Paris 241
Rennes 176

CALAIS:
Caen 120
Nancy 534
Paris 297

I am trying to convert this to a dictionary with the capitalized words as the keys. It should look like this:

roads = {'BREST': ['Rennes'],
         'RENNES': ['Brest', 'Caen', 'Nantes', 'Paris'],
         'CAEN': ['Calais', 'Paris', 'Rennes'],
         'CALAIS': ['Caen', 'Nancy', 'Paris']
         }

Upvotes: 0

Views: 39

Answers (1)

greenBox
greenBox

Reputation: 552

Assuming that you are reading from a file called input.txt, this produces the desired result.

from collections import defaultdict

d = defaultdict(list)

with open('input.txt', 'r') as f:
    for line in f.read().splitlines():
        if not line: continue

        if line.endswith(':'):
            name = line.strip(':')
        else:
            d[name].append(line.split()[0])

If you want to keep the numbers, you can create a dictionary for each each entry in the file and store the contact with the associated number.

from collections import defaultdict

d = defaultdict(dict)

with open('input.txt', 'r') as f:
    for line in f.read().splitlines():
        if not line: continue

        if line.endswith(':'):
            name = line.strip(':')
        else:
            contact, number = line.split(' ')
            d[name][contact] = int(number)

Which produces the following dictionary.

{'BREST': {'Rennes': 244},
 'CAEN': {'Calais': 120, 'Paris': 241, 'Rennes': 176},
 'CALAIS': {'Caen': 120, 'Nancy': 534, 'Paris': 297},
 'RENNES': {'Breast': 244, 'Caen': 176, 'Nantes': 107, 'Paris': 348}}

Upvotes: 1

Related Questions