Converting file to dict

dictionary, file, python, string

Solution

Loop over the file object, line by line, then split the lines:

with open('inputfilename.txt') as menu:
    d = {}
    for line in menu:
        key, value = line.split(None, 1)
        d[key] = value.strip()
    return d

The `.split(None, 1)` call applies the default split algorithm (split on arbitrary-width whitespace), but limits it to just one split to return just 2 items. The advantage is that lines that start with whitespace (such as the `' 8 Shrimp roll'` line in your post) are handled correctly too as the leading whitespace is removed before splitting.

This produces:

{'2': 'Green tea', '1': 'Chocolate ice cream', '8': 'Shrimp roll'}

Problem

How would I take the contents of the file and change it into a dictionary? The contents would include menu items in this form: ``` 1 Chocolate ice cream 2 Green tea 8 Shrimp roll ``` And I want the key to be the number and the value to be the food item. So far, I got: ``` d = {} for line in menu.read().strip().split(): d[line[0]] = d[line[1:]] return d ``` But this comes out skewed...

Original source