Anonymous
Anonymous

Reputation: 11

How to covert a text file into a dictionary in python

I have a text file and am wondering how to make the values inside a dictionary. Right now I have this.

def load_map(map_file_name):
    my_map = open(map_file_name, 'r')
    my_line = my_map.readlines()
    dict = {}

for lines in my_line:
    my_line = lines.split()
    dict[int(my_line[0])] = ','.join(my_line[1:])
    lines.strip('\n')
    lines.split(',')
    print(lines)

The text file I have is

The Dorms
        McDonald's, 50
        Burger King, 100
        Starbucks, 120
McDonald's
        Starbucks, 50
        Taco Bell, 60

I need it to be in the format:

{'The Dorms': {'McDonalds': ' 50', 'Burger King': ' 100', 
'Starbucks': ' 120'}, 
'McDonalds': {'Starbucks': ' 50', 'Taco Bell': ' 60'}

Upvotes: 0

Views: 37

Answers (1)

Eric Truett
Eric Truett

Reputation: 3010

If the pattern holds, then a line that starts with a word is a key for the outer dictionary, and a line that starts with whitespace is a key, value pair for the inner dictionary. Using defaultdict will prevent you from having to test if a key exists in the outer dictionary.

from collections import defaultdict
import re

vals = defaultdict(dict)    
with open(map_file_name, 'r') as f:
    # if the line starts with a character, it is a dict key
    # if it does not, then it is part of the value
    dict_key = None
    for line in f:    
        if re.match(r'\w', line):
            dict_key = line.strip()
        else:
            # split Starbucks, 50 on ', '
            inner_key, inner_value = line.split(', ')
            vals[dict_key][inner_key.strip()] = inner_value.strip()

>>>vals
defaultdict(dict,
            {'The Dorms': {"McDonald's": '50',
              'Burger King': '100',
              'Starbucks': '120'},
             "McDonald's": {'Starbucks': '50', 'Taco Bell': '60'}})

Upvotes: 1

Related Questions