user2884964
user2884964

Reputation: 33

Opening a text file and then storing the contents into a nested dictionary in python 2.7

I'm fairly new to Python, and computing languages in general. I want to open a text file and then store its contents in a nested dictionary. Here's my code so far:

inputfile = open("Proj 4.txt", "r")
for line in inputfile:
    line = line.strip()
    print line
NGC = {}

inputfile.close()

I know I need to use the add operation for dictionaries I'm just unsure how to proceed. Here's a copy of the text file:

NGC0224
Name: Andromeda Galaxy
Messier: M31
Distance: 2900
Magnitude: 3.4
NGC6853
Name: Dumbbell Nebula
Messier: M27
Distance: 1.25
Magnitude: 7.4
NGC4826
Name: Black Eye Galaxy
Messier: M64
Distance: 19000
Magnitude: 8.5
NGC4254
Name: Coma Pinwheel Galaxy
Messier: M99
Distance: 60000
Brightness: 9.9 mag
NGC5457
Name: Pinwheel Galaxy
Messier: M101
Distance: 27000
Magnitude: 7.9
NGC4594
Name: Sombrero Galaxy
Messier: M104
Distance: 50000

Upvotes: 3

Views: 985

Answers (2)

inspectorG4dget
inspectorG4dget

Reputation: 114025

with open(infilepath) as infile:
  answer = {}
  name = None
  for line in infile:
    line = line.strip()
    if line.startswith("NGC"):
      name = line
      answer[name] = {}
    else:
      var, val = line.split(':', 1)
      answer[name][var.strip()] = val.strip()

Output with your text file:

>>> with open(infilepath) as infile:
...   answer = {}
...   name = None
...   for line in infile:
...     line = line.strip()
...     if line.startswith("NGC"):
...       name = line
...       answer[name] = {}
...     else:
...       var, val = line.split(':', 1)
...       answer[name][var.strip()] = val.strip()
... 
>>> answer
{'NGC6853': {'Messier': 'M27', 'Magnitude': '7.4', 'Distance': '1.25', 'Name': 'Dumbbell Nebula'}, 'NGC4254': {'Brightness': '9.9 mag', 'Messier': 'M99', 'Distance': '60000', 'Name': 'Coma Pinwheel Galaxy'}, 'NGC4594': {'Messier': 'M104', 'Distance': '50000', 'Name': 'Sombrero Galaxy'}, 'NGC0224': {'Messier': 'M31', 'Magnitude': '3.4', 'Distance': '2900', 'Name': 'Andromeda Galaxy'}, 'NGC4826': {'Messier': 'M64', 'Magnitude': '8.5', 'Distance': '19000', 'Name': 'Black Eye Galaxy'}, 'NGC5457': {'Messier': 'M101', 'Magnitude': '7.9', 'Distance': '27000', 'Name': 'Pinwheel Galaxy'}}

Upvotes: 2

neves
neves

Reputation: 39343

You have to define better how you want this data mapped to a dictionary. I you can change the file format, it would be nice to reformat it as a standard INI file. You could read it with the ConfigParser module.

But if you really want to go this way. Here is a quick and dirty solution:

d = {}
k = ''
for line in open('Proj 4.txt'):
    if ':' in line:
        key, value = line.split(':', 1)
        d[k][key] = value.strip()
    else:
        k = line.strip()
        d[k] = {}

The dict d has the parsed file.

Upvotes: 0

Related Questions