python - 从文本文件创建字典 2 个值

标签 python function dictionary

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/

相关文章:

python - 如何使用 popen 对输出进行管道传输?

python - web2py - 显示网格中的对象列表

php - 函数只返回一个元素

r - ggfortify::autoplot 或 ggfortify::::autoplot 不工作

ios - 比较两个字典值给我一个 NSInvalidArgumentException

python - 从 ftp 下载并行文件

python - 分割线不丢失定界符

c - C 和 C 结构的新手 -- 如何将结构作为函数中的参数

python - 如何使字典只读?

python - 如何找到字典中哪个键具有最长的值列表?