从带有标题的文本文件创建字典

时间:2017-09-18 11:26:18

标签: python python-2.7

我有一个文本文件test.txt

col1|col2|col3
1|a|123
2|b|456

我想创建一个python字典,其中列为键,相应的值为python中的值。

3 个答案:

答案 0 :(得分:1)

d = {}
with open("test.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val

或者,如果您运行的是python 2.7,则可以使用Dict Comprehensions

答案 1 :(得分:0)

dict = {}

read = open("test.txt")
for l in read:
        l = l.split("|")
        dict.update({l[0]:l[1:]})
print(dict)

它有效

答案 2 :(得分:0)

以下代码对我有用:

read = open("test.txt")
a=[]
for z in read:
    a.append( z.split("|"))
dict = {}
for i in range(len(a)):
    if i == 0:
        for j in a[i]:
            dict[j] = []
    else :
        for j in range(len(a[i])):
            dict[a[0][j]].append( a[i][j])
print(dict)

output: {'col1': ['1', '2'], 'col2': ['a', 'b'], 'col3\n': ['123\n', '456']}