【发布时间】:2012-11-22 20:03:46
【问题描述】:
所以我有一个文本文件,例如:
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
【问题讨论】:
-
您遇到的错误是什么?如果您在问题中包含完整的回溯,它将帮助我们帮助您进行调试。
-
哦,对了,对不起。我现在添加了错误。
-
这是家庭作业吗,@Artorius?我正在写一个答案,但如果这是你应该学习的东西,我不想为你做太多的工作。
-
是的。我已经有了答案,但我想让它更简单,这就是我在上面遇到错误时所尝试的......@Blckknght
-
基本上我正在寻找最简单的代码来做同样的事情。我不确定这是否可能,或者我在这里写的代码是否已经足够了。
标签: python python-3.x dictionary input