猿问

将文本文件读取为 dict

我的文本文件看起来像这样..每行由一个空格分隔。


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


森栏
浏览 253回答 3
3回答

青春有我

对于 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] = valuesfor k in d :    print(k , d[k])

元芳怎么了

你可以这样试试。输入.txtdream 4.345 0.456 6.3456play 0.1223 -0.345 5.3543faster 1.324 2.435 -2.2345编写器.pyoutput_text = '' # Textd = {} # Dictionarywith 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 lineprint(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)输出.txtdream: [4.345 0.456 6.3456]play: [0.1223 -0.345 5.3543]faster: [1.324 2.435 -2.2345]

萧十郎

这很简单。请参阅下面的代码。  dictionary = {}  with open("text.txt", "r") as file:        for lines in file:          line = lines.split()          dictionary[line[0]] = line[1:]  print(dictionary)
随时随地看视频慕课网APP

相关分类

Python
我要回答