Python - Reading a text file into dictionary

38,673

Solution 1

You can do:

for line in f:
    listedline = line.strip().split('=') # split around the = sign
    if len(listedline) > 1: # we have the = sign in there
        newDict[listedline[0]] = listedline[1]

However, what do you want to do with the data stored in this dict? It will store everything as strings so your list will be a big string. If you need more refined data, it's not too hard but you will have to tell us what it is you want to accomplish with this dict.

Solution 2

If you can't control your input text files, you can parse them with (potentially unsafe, so make sure of input) eval, see demo:

source = """@text {
    n = "test1",
    r = ["B:1", "G:2", "H:3", "O:4", "S:5", "W:6"],
    t = ["G:1","H:2"]
}"""
nrt = ' '.join(source.splitlines()[1:4])

here nrt is space-joined lines with n, r and t definition. To make it valid python code, wrap with dict(..), and eval result:

obj_code = 'dict({})'.format(nrt)
result = eval(obj_code)

And finally:

>>> result
{'r': ['B:1', 'G:2', 'H:3', 'O:4', 'S:5', 'W:6'], 't': ['G:1', 'H:2'], 'n': 'test1'}
Share:
38,673
user3071524
Author by

user3071524

Updated on December 09, 2020

Comments

  • user3071524
    user3071524 over 3 years

    I recently started programming with Python and i've encountered quite a big problem with one of my functions. I'm trying to take data from a text file in the form of a list, into a dictionary in Python. The format of the text file is consistently formatted as is displayed below:

    @text {
        n = "test1",
        r = ["B:1", "G:2", "H:3", "O:4", "S:5", "W:6"],
        t = ["G:1","H:2"]
    }
    

    Using the three keys: n, r and t; how would I go about reading their values from the text file into my dictionary using Python?

    So far, I have managed to develop the following code with no success, not knowing where i've gone wrong despite attempting to research this all over the web.

    f = open('text.txt', 'r')
    newDict = {}
    for line in f:
        n, r, t = line.strip().split('=')
        newDict[k.strip()] = v.strip()
    

    Am I along the right lines with this or completely off the mark? The whole concept of reading multiple keys and values into a dictionary from a text file has me completely confused when it comes to the process of importing/converting the file.

    Any help with this would be greatly appreciated - thank you in advance.

  • user3071524
    user3071524 over 10 years
    I'm not sure you understand what I'm looking for from the program although you may be right. I'm basically wanting to import values from a text-based database using the same format as displayed above. The example above is merely one record of a large quantity i'm looking to read into the program BUT because i'm wanting to create a dictionary from the three keys and their corresponding values, I can't simply read the entire text file into the dictionary. Does this help? Please let me know if you want me to elaborate any further to avoid confusion, thanks.
  • user3071524
    user3071524 over 10 years
    Using the data stored in this dictionary from the text-based database file, i'll be prompting the user for input which will then be used to read from the dictionary using the keys and values displayed above from the one example record. In terms of refining the data, I don't want to read the entire text file. I want to read the three keys and their corresponding values into one single dictionary within Python. Is this possible or is there an easier way of doing this? If you need me to elaborate any further, let me know. Thanks.
  • user3071524
    user3071524 over 10 years
    I'm not sure this is what I want to be honest. I'm looking for a way to import the text files keys and corresponding values into one singular dictionary within Python for further user input, rather than manually entering these keys/values into Python myself. Is this possible? Thanks.
  • Steve P.
    Steve P. over 10 years
    @user3071524 I'm incredibly busy right now, but when I get time, I'll try to respond to you.
  • alko
    alko over 10 years
    @user3071524 don't get your comment. do you mean n, r, t? those aren't hardcoded, but parsed. or B:1, G:2 part? it is not a valid sintax and not clear what you expect to get. Please clarify.
  • hansolo
    hansolo about 7 years
    +1 for the simplicity. However stripping key and element may be useful: newDict[listedline[0].strip()] = listedline[1].strip()