Reading files into dictionaries

2019-09-05 17:26发布

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

2条回答
老娘就宠你
2楼-- · 2019-09-05 17:33

Here is another way:

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

Outputs:

{'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.'}
查看更多
我只想做你的唯一
3楼-- · 2019-09-05 17:49

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}
查看更多
登录 后发表回答