Python 将文件读入词典
我正试着把文件读入字典。Python 将文件读入词典,python,file,dictionary,Python,File,Dictionary,我正试着把文件读入字典。lane.split()方法将不起作用,因为我正在将文件格式化为多行,且空格太多 in inventory2 (item, description) = line.split() ValueError: too many values to unpack 这是我的文本文件。键\n值 Key A rusty old key, you used it to gain entry to the manor. A stick You found it on your
lane.split()
方法将不起作用,因为我正在将文件格式化为多行,且空格太多
in inventory2
(item, description) = line.split()
ValueError: too many values to unpack
这是我的文本文件。键\n值
Key
A rusty old key, you used it to gain entry to the manor.
A stick
You found it on your way in, it deals little damage.
Health potion
A health potion, it can restore some health.
对此的任何解决方案都将不胜感激
def inventory2():
inventory_file = open("inventory_test.txt", "r")
inventory = {}
for line in inventory_file:
(item, description) = line.split()
inventory[(item)] = description
#invenory = {inventory_file.readline(): inventory_file.readline()}
print(line)
inventory_file.close
您正在文件中的每一行上循环,因此永远不会有一行同时包含键和值。使用获取给定键的下一行:
def inventory2():
with open("inventory_test.txt", "r") as inventory_file:
inventory = {}
for line in inventory_file:
item = line.strip()
description = next(inventory_file).strip()
inventory[item] = description
return inventory
或者,更简洁地理解dict:
def inventory2():
with open("inventory_test.txt", "r") as inventory_file:
return {line.strip(): next(inventory_file).strip() for line in inventory_file}
还有一种方法:
def inventory2():
inventory_file = open("inventory_test.txt", "r")
inventory = {}
lines = inventory_file.readlines()
x = 0
while (x < len(lines)):
item = lines[x].strip()
description = lines[x+1].strip()
inventory[item] = description
x += 2
print inventory
return inventory
{'Health potion': 'A health potion, it can restore some health.', 'A stick': 'You found it on your way in, it deals little damage.', 'Key': 'A rusty old key, you used it to gain entry to the manor.'}