user2489861
user2489861

Reputation: 109

Converting file to dict

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

Upvotes: 3

Views: 193

Answers (4)

Óscar López
Óscar López

Reputation: 235994

How about a dictionary comprehension?

{ k:v.strip() for k, v in (line.split(None, 1) for line in menu) }

Upvotes: 2

Sukrit Kalra
Sukrit Kalra

Reputation: 34493

>>> finalDict = {}
>>> with open('fileName.txt', 'r') as f:
        for line in f:
            key, elem = line.strip().split(" ", 1)
            finalDict[int(key)] = elem


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

We iterate over each line of the file, stripping it, then splitting it on the first space.

Upvotes: 2

jh314
jh314

Reputation: 27802

You can try this:

d = {}
for line in menu.read().strip().split():
      d[line[0]] = line[1:] # you want to use just line[1:], than d[line[1:]]
return d

The issue here is that d[line[1:]] gives you the value mapped by the key line[1:].

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121486

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

Upvotes: 5

Related Questions