将文本文件读取为dict

时间:2019-03-19 03:37:16

标签: python python-3.x

我的文本文件如下所示。每行之间用空格隔开。

dream 4.345 0.456 6.3456
play 0.1223 -0.345 5.3543
faster 1.324 2.435 -2.2345

我要写字典并按如下所示打印它...

dream: [4.345 0.456 6.3456]
play: [0.1223 -0.345 5.3543]
faster: [1.324 2.435 -2.2345]

我的代码如下。请用这个来纠正我...

with open("text.txt", "r") as file:
     for lines in file:
        line = lines.split()
        keys = b[0] 
        values = b[1:]
        d[keys] = values
print d

3 个答案:

答案 0 :(得分:0)

对于python3,如果您想获得想要的结果:

d = {}

with open("text.txt", "r") as file:
    for lines in file:
    line = lines.split()
    keys = line[0] 
    values = list(map(float, line[1:]))
    d[keys] = values
for k in d :
    print(k , d[k])

答案 1 :(得分:0)

这很简单。请参见下面的代码。

  dictionary = {}
  with open("text.txt", "r") as file:  
      for lines in file:
          line = lines.split()
          dictionary[line[0]] = line[1:]
  print(dictionary)

答案 2 :(得分:0)

您可以尝试这样。

  

input.txt

dream 4.345 0.456 6.3456
play 0.1223 -0.345 5.3543
faster 1.324 2.435 -2.2345
  

writer.py

output_text = '' # Text
d = {} # Dictionary

with open("input.txt") as f:
    lines = f.readlines()

    for line in lines:
        line = line.strip()
        arr = line.split()
        name = arr[0]
        arr = arr[1:]

        d[name] = arr
        output_text += name + ": [" + ' '.join(arr) + "]\n"

output_text = output_text.strip() # To remove extra new line appended at the end of last line

print(d)
# {'play': ['0.1223', '-0.345', '5.3543'], 'dream': ['4.345', '0.456', '6.3456'], 'faster': ['1.324', '2.435', '-2.2345']}

print(output_text)
# dream: [4.345 0.456 6.3456]
# play: [0.1223 -0.345 5.3543]
# faster: [1.324 2.435 -2.2345]

with open("output.txt", "w") as f:
    f.write(output_text)
  

output.txt

dream: [4.345 0.456 6.3456]
play: [0.1223 -0.345 5.3543]
faster: [1.324 2.435 -2.2345]