Python 从文件到字典

Python 从文件到字典,python,dictionary,Python,Dictionary,我想把一个文件放进字典里。 文件如下所示: 1 some something something 2 go goforit doit 17 non so 我正在尝试类似的方法,但不起作用: def filetodic(): d={} with open("file.txt") as f: for line in f: key = line.split() return d print filetodic() 编辑:字典中每个字段的键必须是文件中每行中第一个元素的数字 试

我想把一个文件放进字典里。 文件如下所示:

1 some something something
2 go goforit doit 
17 non so 
我正在尝试类似的方法,但不起作用:

def filetodic():
 d={}
 with open("file.txt") as f:
  for line in f:
   key  = line.split()
 return d
print filetodic()
编辑:字典中每个字段的键必须是文件中每行中第一个元素的数字

试试这个:

def filetodic():
    d={}
    f = open("file.txt")
    for line in f:
        key  = line.split()
        d[key[0]]= ' '.join(key[1:])
    return d

print filetodic()
试试这个:

def filetodic():
    d={}
    f = open("file.txt")
    for line in f:
        key  = line.split()
        d[key[0]]= ' '.join(key[1:])
    return d

print filetodic()
既然您想要
{1:“一些东西”,2:“GoForItDoit”}
(如注释中所示),请尝试

请注意,这会保留值本身的间距(例如,
1abc def
变为
1:'abc def'
,而不是
1:'abc def'
)。

既然您想要
{1:'some something something',2:“goforit doit”
(如注释中所示),请尝试


请注意,这将保留值本身的间距(例如,
1 abc def
变为
1:“abc def”
,而不是
1:“abc def”
)。

正则表达式:

rg = re.compile(r'(?P<k>[0-9]+)[ \t]+(?P<v>[A-Za-z\t .]+)')

def filetodic(fileo):
    return {int(k):v.strip() for k,v in [rg.match(line).groups() for line in fileo]}

print filetodic(open("test.txt"))
rg=re.compile(r'(?P[0-9]+)[\t]+(?P[A-Za-z\t.]+))
def filetodic(文件O):
返回{int(k):v.strip()表示k,v在[rg.match(line).groups()表示文件中的行]}
打印文件TODIC(打开(“test.txt”))

使用正则表达式:

rg = re.compile(r'(?P<k>[0-9]+)[ \t]+(?P<v>[A-Za-z\t .]+)')

def filetodic(fileo):
    return {int(k):v.strip() for k,v in [rg.match(line).groups() for line in fileo]}

print filetodic(open("test.txt"))
rg=re.compile(r'(?P[0-9]+)[\t]+(?P[A-Za-z\t.]+))
def filetodic(文件O):
返回{int(k):v.strip()表示k,v在[rg.match(line).groups()表示文件中的行]}
打印文件TODIC(打开(“test.txt”))

你想让字典看起来像什么?那么,
{1:“some”,2:“go”}
,或者
{1:“some”,2:(“go”,“goforit”,“doit”)}
,或者
{1:(“some”,“something”,“something”),2:(“go”,“goforit”,“doit”)}
,或者完全是别的什么?你还是不太清楚……你想要这本字典是什么样子的?那么,
{1:“some”,2:“go”}
,或者
{1:“some”,2:“go”,“goforit”,“doit”)}
,或者
{1:(“some”,“something”,“something”),2:(“go”,“goforit”,“doit”)}
?您仍然不太清楚…每个元素的末尾都有一个
\n
您能告诉我每行的含义吗?第一行删除尾随空格(
.rstrip
),然后在空格上最多拆分一次行(
拆分(无,1)
)。下一行将键转换为int(
int(k)
)并设置字典条目(
d[…]=v
)。这一行在每个元素的末尾都有一个
\n
你能告诉我每一行的含义吗?第一行删除后面的空白(
.rstrip
),然后在空白处最多拆分一行(
split(None,1)
)。下一行将键转换为int(
int(k)
)并设置字典条目(
d[…]=v
)。
d[key[0]=''。join(key[1:])
您能解释一下这一行的含义吗?
key=line.split将以空格分隔该行作为分线符(连续的空格作为一个完整的1空格计算)并返回一个包含所有单词的列表。和
d[key[0]]=''。join(key[1:])
将列表的第一个元素指定为字典的键,列表的其余部分指定为值。
d[key[0]]=''。join(key[1:])
你能解释一下这一行的含义吗?
key=line.split()
将把这一行与空格分割成一个分隔符(连续的空格作为一个完整的1个空格计算),并返回一个包含所有单词的列表。和
d[key[0]=''。join(key[1:])
将列表的第一个元素指定为字典的键,列表的其余部分指定为值。