Search code examples
pythondictionaryread-text

How can i make a dictionary from txt file in python


I have get this txt file

A:{A:0, B:6, C:4, D:3, E:0, F:0, G:0}

B:{A:6, B:0, C:2, D:0, E:4, F:0, G:0}

C:{A:4, B:2, C:0, D:2, E:0, F:8, G:0}

D:{A:3, B:0, C:2, D:0, E:3, F:0, G:0}

E:{A:0, B:4, C:0, D:3, E:0, F:7, G:6}

F:{A:0, B:0, C:8, D:0, E:7, F:0, G:6}

G:{A:0, B:0, C:0, D:0, E:6, F:6, G:0}


titles = []


with open("graph.txt", "r") as file:

    for line in file:
        column=line.split(":")
        title=column[0]
        titles.append(title)

i need to make dictionaries for each title which i got like A,B,C


Solution

  • Format each line properly and you can use ast.literal_eval. I used regex to find each key and replace it with the same key surrounded by quotes.

    import ast
    import re
    KEY_PATTERN = re.compile(r'(\w+?):')
    dics = []
    with open('graph.txt') as f:
        for line in f:
            line = line.strip()
            if line:
                dic_str = "{" + KEY_PATTERN.sub(r'"\g<1>":', line) + "}"
                dics.append(ast.literal_eval(dic_str))
    print(dics)
    

    Can be shorter (though harder to read):

    import ast
    import re
    KEY_PATTERN = re.compile(r'(\w+?):')
    
    with open('graph.txt') as f:
        dics = [ast.literal_eval("{" + KEY_PATTERN.sub(r'"\g<1>":', line) + "}") for line in f if line.strip()]
    print(dics)
    

    Output:

    [{'A': {'A': 0, 'B': 6, 'C': 4, 'D': 3, 'E': 0, 'F': 0, 'G': 0}}, {'B': {'A': 6, 'B': 0, 'C': 2, 'D': 0, 'E': 4, 'F': 0, 'G': 0}}, {'C': {'A': 4, 'B': 2, 'C': 0, 'D': 2, 'E': 0, 'F': 8, 'G': 0}}, {'D': {'A': 3, 'B': 0, 'C': 2, 'D': 0, 'E':3, 'F': 0, 'G': 0}}, {'E': {'A': 0, 'B': 4, 'C': 0, 'D': 3, 'E': 0, 'F': 7, 'G': 6}}, {'F': {'A': 0, 'B': 0, 'C': 8, 'D': 0, 'E': 7, 'F': 0, 'G': 6}}, {'G': {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 6, 'F': 6, 'G': 0}}]
    

    If you want the result to be just one dict than change:

    dics = []
    # and
    dics.append(ast.literal_eval(dic_str))
    

    to

    dics = {}
    # and
    dics.update(ast.literal_eval(dic_str))