Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read file into dictionary in Python specific filetype

Specifically, I have a text file with multiple lines arranged so that the key of each entry is the first line of a group, followed by its related values, followed by a newline before the next key. I'm having a hard time using while loops to accomplish this with readline.

For example the first line may be a restaurant name, followed by several lines of customers who ate there, which I then need to write into the values of a dictionary under the key of a restaurant name.

I'm really unfamiliar with file reading so I'm afraid that what I have is not going to help at all really.

Something like this I guess, but it's not even to the point of semi-functional.

edit: Thanks for the response I should have clarified, each value item for a corresponding key is listed in subsequent lines after the key with the a blank line at the end of that list preceding the next key. Also I am unfortunately compelled to use a readline approach here.

    restaurants = {}
    patrons = []

    line = file.readline()
    s = line.strip('\n')

    while s != ''
    restaurant = s
    line = file.readline
    patrons.append(s)
like image 651
JD3 Avatar asked Dec 30 '25 13:12

JD3


1 Answers

Assuming your text file looks like this

mcdonalds bill bo bob

as per

I have a text file with multiple lines arranged so that the key of each entry is the first line of a group, followed by its related values, followed by a newline

my_dict = {}

with open("rest.txt", 'r') as f:
    for line in f:
        items = line.split()
        key, values = items[0], items[1:]
        my_dict[key] = values


print my_dict

which will produce

{'mcdonalds': ['bill', 'bo', 'bob']}
like image 77
John Avatar answered Jan 02 '26 03:01

John



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!