Skip to content
Advertisement

turn a multiple line of txt file into a dictionary

I have a multiple line of text like:

fischer morphy 1 - 0
carlsen alekhine 0 - 1-
kasparov capablanca 1/2 - 1/2

and I need a way to read the txt file, and turn it into a dictionary like this

    # match result dictionary
match_result = [ # dict name
    {
        "match": "1",           # match
        "wht_ply": "fischer",   # white player name
        "blck_ply": "morphy",   # black player name
        "wht_scr":"1",          # white player score
        "dash":"-",             # unused dash
        "blck_scr":"0"          # black player score
    },

so i can use

        for item in match_result:
        if item["wht_scr"] and item["blck_scr"] == "1/2":
            print("match",item["match"],"game between white player",item["wht_ply"],"and black player",item["blck_ply"],"ended up in draw")

and get the result of match that ended in draw

is there a way to achieve this?

Advertisement

Answer

I would suggest to use a .json file, this way:

{
    '1': ['Fischer', 'Morphy', 1, 0],
    '2': ['Carlsen', 'Alekhine', 0, 1] # Did this match has never been disputed in reality, right?
}

The parsing would be done this way:

import json
with open('file.json', 'r+') as file:
    matches = json.load(file)
for i in matches.keys():
    print(f"Match {i}: {matches[i][0]} {matches[i][2]} - {matches[i][1]} {matches[i][3]}")

It is possible to parse a .txt file too, even if it’s a bad practice to store datas this way. When I suggested to store a dictionary in a .txt file in a way similar to yours, one expert told me:

Unless you want to reinvent the wheel, you should use a .json file


You can anyway split the lines this way:

with open('file.txt', 'r') as file:
    lines = file.read().split('n') # lines is a list of the lines of the file
dictionary: dict = {}
for index, line in enumerate(lines):
    line = line.split(' ')
    dictionary[str(index)] = {
        "white": line[0],
        "black": line[1],
        "white score": line[2],
        "black score": line[4]
    }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement