上記のいずれかを変更すると、次のようになります。
def read_next_object(file):
obj = {}
for line in file:
if not line.strip(): continue
line = line.strip()
key, val = line.split(": ")
if key in obj and key == "Object":
yield obj
obj = {}
obj[key] = val
yield obj
planets = {}
with open( "test.txt", 'r') as f:
for obj in read_next_object(f):
planets[obj["Object"]] = obj
print planets
の大文字と小文字を修正してくださいRootObject
。これが、投稿したサンプル データから探している最終的な辞書であると思います。それは、各惑星がその情報の辞書である惑星の辞書です。
print planets["Sun"]["Radius"]
値を出力する必要があります20890260
上記の出力は次のようになります。
{ 'Earth': { 'Object': 'Earth',
'Orbital Radius': '77098290',
'Period': '365.256363004',
'Radius': '6371000.0',
'Satellites': 'Moon'},
'Moon': { 'Object': 'Moon',
'Orbital Radius': '18128500',
'Period': '27.321582',
'Radius': '1737000.10'},
'Sun': { 'Object': 'Sun',
'Orbital Radius': '0',
'Radius': '20890260',
'RootObject': 'Sun',
'Satellites': 'Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Ceres,Pluto,Haumea,Makemake,Eris'}}