将文件读入字典

时间:2013-11-25 22:33:50

标签: 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 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

2 个答案:

答案 0 :(得分:2)

您正在循环文件中的每一行,因此永远不会有包含键和值的行。使用next() function来获取给定密钥的下一行:

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

或者,更加紧凑,具有词典理解力:

def inventory2():
    with open("inventory_test.txt", "r") as inventory_file:
        return {line.strip(): next(inventory_file).strip() for line in inventory_file}

答案 1 :(得分:0)

这是另一种方式:

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.'}