所以我有一个文本文件,例如:
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
我正在尝试将其输入字典。这是我到目前为止所拥有的,但我不断收到错误...
#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)
我应该得到这样的东西:
{' 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'}}
我收到此错误:
Traceback (most recent call last):
File "planet2.py", line 21, in <module>
for d in data(x):
TypeError: 'NoneType' object is not iterable