Reading files into dictionaries

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

Answers


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}

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

Need Your Help

How do I multithread an API query in Python and store the results in a csv file?

python csv dictionary python-requests python-multithreading

I am new to Python and was writing a simple query to get information from the USPS API and store the results in a .csv file that I could reference later. I can successfully query the API, but I would

What's the most "death-resistant" component on Android?

android android-asynctask android-service android-lifecycle

I'm looking for the most suitable class to be a dispatcher for AsyncTasks invoked from my Activities.