0 python dictionary text-files python-3.x valueerror
我有一个类似这样的文本文件:
banana
delicious
yellow
watermelon
big
red
orange
juicy
vitamin c
Run Code Online (Sandbox Code Playgroud)
我正在尝试将此文本文件转换为字典(水果名称作为键,它的几行描述作为各种值)。以下是我当前的代码。
f = open("filepath", 'w')
myplant = {}
for line in f:
k, v = line.strip().split('\n\n')
myplant[k.strip()] = v.strip()
f.close()
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
ValueError: not enough values to unpack (expected 2, got 1)
Run Code Online (Sandbox Code Playgroud)
谁能帮我调试我的问题。谢谢!
myplant = dict((i[0], i[1:3]) for i in (line.strip().split('\\n') for line in f if line != '\n') if i)
print(myplant)
Run Code Online (Sandbox Code Playgroud)
输出:
{'banana ': [' delicious ', ' yellow '],
'watermelon ': [' big ', ' red '],
'orange ': [' juicy ', ' vitamin c ']}
Run Code Online (Sandbox Code Playgroud)
我们可以获取到换行符之前的所有值\n并将其存储在一个临时列表中。然后将其存储到数据列表中。
temporary = []
for line in f:
if line.strip().split('\\n')[0]:
if len(line.strip().split('\\n')) > 2:
temporary = list(i.strip() for i in line.strip().split('\\n') if i.strip())
else:
temporary.append(line.strip().split('\\n')[0])
elif temporary:
data.append(temporary)
temporary = []
Run Code Online (Sandbox Code Playgroud)
结果将是:
[['banana', 'delicious', 'yellow'],
['watermelon', 'big', 'red'],
['orange', 'juicy', 'vitamin c']]
Run Code Online (Sandbox Code Playgroud)
现在对于每个列表,第一项将是键,其余是值。
myplant = dict((val[0], val[1:]) for val in data)
Run Code Online (Sandbox Code Playgroud)
输出:
{'banana': ['delicious', 'yellow'],
'watermelon': ['big', 'red'],
'orange': ['juicy', 'vitamin c']}
Run Code Online (Sandbox Code Playgroud)
r从文本文件中读取时应该使用
myplant = dict((i[0], i[1:3]) for i in (line.strip().split('\\n') for line in f if line != '\n') if i)
print(myplant)
Run Code Online (Sandbox Code Playgroud)
返回字典项时使用键值元组。
k = line.strip().split('\\n')
Run Code Online (Sandbox Code Playgroud)
您可以使用k.remove("")删除空字符串。
很长的路要走:
{'banana ': [' delicious ', ' yellow '],
'watermelon ': [' big ', ' red '],
'orange ': [' juicy ', ' vitamin c ']}
Run Code Online (Sandbox Code Playgroud)
简短的方法:
k = [i for i in k if i]
Run Code Online (Sandbox Code Playgroud)
输出:
{'banana ': [' delicious ', ' yellow '],
'watermelon ': [' big ', ' red '],
'orange ': [' juicy ', ' vitamin c ']}
Run Code Online (Sandbox Code Playgroud)
f = open("filepath", 'r')
myplant = {}
for line in f:
k = line.strip().split('\\n')
# while "" in k:
# k.remove("")
k = [i for i in k if i]
if k:
myplant[k[0]] = k[1:]
print(myplant)
f.close()
Run Code Online (Sandbox Code Playgroud)