How to assign lines from text file to Dictionary after matching string until next matching string

Viewed 32

I am trying to get the Resident's into a Dictionary with the residents as members of the residence. This way if I search for Bill, it would return There is a Bill located at Res-Condo-2 and Res-Condo-1. The Text file I am reading from looks like:

************
    Ohio
************
Res-House-1
Mickey
Minnie
Goofy
Res-Apt-1
Fred
Barnie
Wilma
Res-Condo-2
Bill

************
    Ohio
************
Res-House-2
Stan
Francine
Haley
Stve
Res-Condo-1
Bill

I am able to read the file in and create a list of the Residencies, but I am not able to get the other elements. I also noticed that the list contains the New Line at the end.

list = []
with open('Residencies') as f:
  for line in o:
    if "Res" in line:
      list.append(line)
print(list)

Print Statement output

['Res-House-1\n', 'Res-Apt-1\n', 'Res-Codo-2\n', 'Res-House-2\n', 'Res-Condo-1\n']

How can I get each residence in a dictionary so that I can search which resident belongs to which residence?

2 Answers

Lets start with ignoring the irrelevant lines (e.q empty lines, *** etc)

if line.startswith('*') or line.startswith(' '):
    continue
line = line.strip()

if not line:
    continue

Now just keep track of last residence you have seen. All the names followed by that residence live there. Put this information in a dictionary with key as the person name and value as the list of residences.

from collections import defaultdict

home = defaultdict(list)
last = None

with open('Residencies') as f:
    for line in f:
        if line.startswith('*') or line.startswith(' '):
            continue
        line = line.strip()

        if not line:
            continue

        if 'Res' in line:
            last = line
        else:
            home[line].append(last)

print(home['Bill'])

Output: ['Res-Condo-2', 'Res-Condo-1']

Also, it is not a good idea to have list as name of a variable.

Grouping residents by residencies:

from collections import defaultdict

with open('Residencies.txt') as f:
    residencies = defaultdict(list)
    for line in f:
        line = line.strip()
        if not line: continue   # skip empty line
        if line.startswith('**'):   # skip *** state block
            next(f)
            next(f)
            continue
        if line.startswith('Res'):
            k = line
            continue
        residencies[k].append(line)

    print(dict(residencies))

The output:

{'Res-Apt-1': ['Fred', 'Barnie', 'Wilma'],
 'Res-Condo-1': ['Bill'],
 'Res-Condo-2': ['Bill'],
 'Res-House-1': ['Mickey', 'Minnie', 'Goofy'],
 'Res-House-2': ['Stan', 'Francine', 'Haley', 'Stve']}
Related