So I have a text file for example:
RootObject: Sun
Object: Sun
Satellites: Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Ceres,Pluto,Haumea,Makemake,Eris
Radius: 20890260
Orbital Radius: 0
Object: Earth
Orbital Radius: 77098290
Period: 365.256363004
Radius: 6371000.0
Satellites: Moon
Object: Moon
Orbital Radius: 18128500
Radius: 1737000.10
Period: 27.321582
and I'm trying to input it into a dictionary. This is what I have so far but I keep getting an error...
#d = dictionary
#new_d = new dictionary
file = open("data.txt","r")
d = {}
def data(file):
for line in file:
if line != line.strip:
continue
line = line.strip()
key = line.split(":")
val = line.split(":")
if key in d and key == "Object":
print(d)
d[key] = val
print(d)
new_d = {}
with file as x:
for d in data(x):
new_d[d["Object"]] = d
print(nd)
I should be getting something like this:
{' Earth': {'Satellites': ' Moon', 'Orbital Radius': ' 77098290', 'Object': ' Earth', 'Radius': ' 6371000.0', 'Period': ' 365.256363004'}, ' Moon': {'Orbital Radius': ' 18128500', 'Object': ' Moon', 'Radius': ' 1737000.10', 'Period': ' 27.321582'}, ' Sun': {'Satellites': ' Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Ceres,Pluto,Haumea,Makemake,Eris', 'Orbital Radius': ' 0', 'Object': ' Sun', 'Radius': ' 20890260', 'RootObject': ' Sun'}}
I get this error:
Traceback (most recent call last):
File "planet2.py", line 21, in <module>
for d in data(x):
TypeError: 'NoneType' object is not iterable
See Question&Answers more detail:
os