如何使用python内置的函数读取文本文件以查找值

如何使用python内置的函数读取文本文件以查找值,python,Python,我有一个在列表中读取的函数。它将遍历列表并将其用作函数输入。它读取仅包含2行的文本文件 LC1 立法会二题 当它输入LC2时,函数立即中断,我不知道为什么。最终目标是拥有一个类似这样的字典 d={LC1:None,LC2:None} 简单的方法: def todict(vals,file): d={} for line in file: if line.rstrip() in vals: d[line.rstrip()]=None

我有一个在列表中读取的函数。它将遍历列表并将其用作函数输入。它读取仅包含2行的文本文件

LC1
立法会二题

当它输入LC2时,函数立即中断,我不知道为什么。最终目标是拥有一个类似这样的字典

d={LC1:None,LC2:None}

简单的方法:

def todict(vals,file):
    d={}
    for line in file:
        if line.rstrip() in vals:
            d[line.rstrip()]=None

    return d

file = open("Text.txt",'r')
print(todict(['LC1','LC2'],file))
但最简单的方法还是:

def todict(vals,file):
    return {}.fromkeys([i.rstrip() for i in file if i.rstrip() in vals])

file = open("Text.txt",'r')
print(todict(['LC1','LC2'],file))
两者都再现了:

{'LC1': None, 'LC2': None}

卸下
else
零件。如果你在第一行没有找到输入,你就破坏了循环。你好!小心——
dict
已经是默认python类()的名称,因此替换它可能是不明智的…
dict.fromkeys(open(“Text.txt”,“r”))
我认为是enough@Anon同时
输入
{'LC1': None, 'LC2': None}