def makeDict(filename):
with open(filename,"r") as f:
dict_={}
for line in f:
(key,value1,value2)=line.split()
dict_[key]=[(float(value1),float(value2))]
mylist=[]
for value1 in dict_:
if number < value1 < number:
mylist.append(key)
最后一个问题我应该在这里完成。看来我的值仍然没有以 float 的形式出现,因为我试图检查该值是否在 2 个数字之间,并且出现此错误
TypeError: unorderable types: int() < str()
newDict=makeDict("file.txt")
>>> testdict(500,530,newDict)
line 28, in testdict
for k,v in newDict.iteritems():
AttributeError: 'dict' object has no attribute 'iteritems'
最佳答案
您的函数makeDict
不返回值。
def makeDict(filename):
with open(filename,"r") as f:
d={}
for line in f:
(key,value1,value2)=line.split()
d[key]=[(float(value1),float(value2))]
# Return the dictionary
return d
编辑
代码中的问题是,当您迭代只有一个值的字典时(在本例中为 value1
),它只会迭代键。您想要的是迭代可以使用方法 .values()
def makeDict(filename):
with open(filename,"r") as f:
dict_={}
for line in f:
(key,value1,value2)=line.split()
dict_[key]=[(float(value1),float(value2))]
mylist=[]
# Iterate through the values instead
for value1 in dict_.values():
if number < value1 < number:
mylist.append(key)
您遇到的最后一个错误可能是由您使用的 Python 版本引起的。请参阅this post .
In Py3.x, things are more clean, since there are only dict.items(), dict.keys() and dict.values() available, which return the view objects just as dict.viewitems() in Py2.x did.
因此,您应该将 testdict
中的代码更改为 for k, v in newDict.items():
关于python - 从文本文件创建字典 2 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37494666/