将文本转换为字典

时间:2015-09-15 20:52:19

标签: python function python-2.7

我想将.txt文件转换为字典。 该文件包含两列字母: 一个 d f g h 是的 你我 你 我尝试了以下代码:

f=open('file.txt')
for line in f:
   letters = line.split() #convert them into a list
   c=tuple(letters) #convert the list to a tuple
   d=dict((y, x) for x, y in c)
print d

我想将所有lettes转换为元组然后将其转换为字典.. {'第一封信':'第二封信'} 但它给了我以下错误:

Traceback (most recent call last):
File "<pyshell#43>", line 4, in <module> d= {y:x for x,y in tpl}
File "<pyshell#43>", line 4, in <dictcomp> d= {y:x for x,y in tpl}
ValueError: need more than 1 value to unpack

如何解决这个问题? 我使用的是Python 2.7

1 个答案:

答案 0 :(得分:1)

file.txt的

a s
d f
g h
t y
u i
y u 

with open ('file.txt', 'rb') as f:
    data = dict([x.split() for x in f.read().splitlines()])
print data
#{'a': 's', 'd': 'f', 'g': 'h', 'u': 'i', 't': 'y', 'y': 'u'}