本文介绍了将文件读入字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从一个文件中读入一本字典。 lane.split()
方法将无法正常工作,因为我通过单独的行格式化文件,空格太多。
$ 2
(item,description)= line.split()
ValueError:要解压的值太多
这是我的文本文件。钥匙
钥匙
一个生锈的旧钥匙,你用它来进入庄园。
一个棒
你发现它在你的路上,它几乎没有损害。
健康药水
一种保健药水,可以恢复身体健康。
对此的任何解决方案将不胜感激。
def inventory2():
inventory_file = open(inventory_test.txt,r)
inventory = {}
在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 = {}
在inventory_file中的行:
item = line.strip()
description = next inventory_file).strip()
库存[item] = description
返回库存
或者更紧凑的一个字母理解:
def inventory2():
with open(inventory_test.txt ,r)as inventory_file:
return {line.strip():next(inventory_file).strip()for inventory_file}
I am trying to read from a file into a dictionary. The lane.split()
method will not work as I am formatting my file over separate lines, with too many spaces.
in inventory2
(item, description) = line.split()
ValueError: too many values to unpack
Here is my text file. Key \n Value.
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.
Any solutions to this would be much appreciated.
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
解决方案
You are looping over each line in the file, so there will never be a line with both key and value. Use the next()
function to get the next line for a given key instead:
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
or, more compact with a dict comprehension:
def inventory2():
with open("inventory_test.txt", "r") as inventory_file:
return {line.strip(): next(inventory_file).strip() for line in inventory_file}
这篇关于将文件读入字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!