Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 334
user2489861 Avatar asked Feb 02 '26 04:02

user2489861


2 Answers

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'}
like image 143
Martijn Pieters Avatar answered Feb 03 '26 17:02

Martijn Pieters


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

like image 25
jh314 Avatar answered Feb 03 '26 17:02

jh314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!