Home > Blockchain >  How to read from a txt file into a dictionary where the value is a nested dictionary and the key of
How to read from a txt file into a dictionary where the value is a nested dictionary and the key of

Time:11-20

I'm trying to load the following a txt file into a dictionary:
['A'] (4)
['B'] (4)
['E'] (4)
['C'] (4)
['A', 'B'] (3)
['A', 'E'] (3)
['A', 'C'] (3)
['B', 'E'] (4)
['B', 'C'] (3)
['C', 'E'] (3)
['A','B', 'E'] (3)
['B', 'C', 'E'] (3)

I want the dictionary to look like this:

itemsets={ A:{"support_count":4},B:{"support_count":4},E:{"support_count":4},C:{"support_count":4},AB:{"support_count":3},AE:{"support_count":3},AC:{"support_count":3},BE:{"support_count":4},BC:{"support_count":3},CE:{"support_count":3},ABE:{"support_count":3},BCE:{support_count:3}}

This is what I have so far:

    keys=[]
    values=[]

    with open(filename, 'r') as f:
        lines = f.readlines()
    keys = [line[:line.find(']')] for line in lines]
    keys = [k.replace('[', '').replace(']', '').replace(',','').replace("'",'').replace(' ','') for k in keys]
    
    values= [line[line.find('('):] for line in lines]
    values = [v.replace('(', '').replace(')', '').replace("'",'').replace("\n",'') for v in values]
    itemsets = dict.fromkeys(keys)
    for v in values:
        for item in itemsets.keys():
            d[item]={"support_count": v}
    return itemsets
This is what I get when I run it:

{'A': {'support_count': '3'}, 'B': {'support_count': '3'}, 'E': {'support_count': '3'}, 'C': {'support_count': '3'}, 'AB': {'support_count': '3'}, 'AE': {'support_count': '3'}, 'AC': {'support_count': '3'}, 'BE': {'support_count': '3'}, 'BC': {'support_count': '3'}, 'CE': {'support_count': '3'}, 'ABE': {'support_count': '3'}, 'BCE': {'support_count': '3'}}

CodePudding user response:

As you iterate over values, you keep overwriting the dict values with the next one, the last being a 3, you need to iterate on both at the same time : zip

for k, v in zip(keys, values):
    d[k] = {"support_count": int(v)}

To parse the data, I'd suggest a regex approach

  • \[(.*)] \((\d ) to parse each line : the keys and the value
  • [^A-Z] to remove non letters from the key
import re

lines = ["['A'] (4)", "['B'] (4)", "['E'] (4)", "['C'] (4)", "['A', 'B'] (3)",
         "['A', 'E'] (3)", "['A', 'C'] (3)", "['B','E'] (4)", "['B', 'C'] (3)",
         "['C', 'E'] (3)", "['A','B', 'E'] (3)", "['B', 'C', 'E'] (3)"]

d = {}
ptn_all = re.compile(r"\[(.*)] \((\d )")
ptn_key = re.compile("[^A-Z]")
for line in lines:
    keys, value = ptn_all.search(line).groups()
    d[ptn_key.sub("", keys)] = {"support_count": int(value)}
  • Related