使用python将列转换为字典

使用python将列转换为字典,python,Python,我已将一些数据导出到文本文件中,以包含两列数据,如下所示: a b c d e f g h 不幸的是,这些列的间距不均匀。a和b可能由2个空格分隔,c和d可能由5个空格分隔,e和f可能由3个空格分隔,等等 如何获取这些列并创建类似{a:b,c:d,e:f,g:h}的简单字典?您可以尝试以下方法: f = [i.strip('\n').split() for i in open('filename.txt')] final_dict = {i[0]:i[1] for i

我已将一些数据导出到文本文件中,以包含两列数据,如下所示:

a   b

c   d

e    f

g  h
不幸的是,这些列的间距不均匀。a和b可能由2个空格分隔,c和d可能由5个空格分隔,e和f可能由3个空格分隔,等等

如何获取这些列并创建类似{a:b,c:d,e:f,g:h}的简单字典?

您可以尝试以下方法:

f = [i.strip('\n').split() for i in open('filename.txt')]

final_dict = {i[0]:i[1] for i in f}

默认情况下,split函数将在空格实例处自动分割行,无论长度如何。

您可以在函数中将自定义的
delim_whitespace
参数设置为
True

import pandas as pd

df = pd.read_table('data.txt', delim_whitespace=True)

d = {a: b for a, b in df.values}

像这样一个简单的解决方案怎么样

d = {}

for line in open('file.txt'):
    [key, value] = line.split() # split() without arguments splits by whitespace
    d[key] = value

print(d)

所有栏目都只包含两个词吗?欢迎访问该网站:您可能需要阅读、和,并相应地重述您的问题。@Marcus很乐意提供帮助!请考虑接受这个答案,因为它对StAccOp溢出社区是有益的。非常感谢。