dan
dan

Reputation: 101

How can I create a dictionary in python from a txt file?

I have a file that looks like this:

NODE=SC-1,CPU=90
NODE=SC-1,MEM=10
NODE=SC-1,FS=80
NODE=SC-1,DIORead=30
NODE=SC-1,DIOWrite=40
NODE=SC-1,NTX=30
NODE=SC-1,NRX=40
NODE=SC-2,CPU=80
NODE=SC-2,MEM=10
NODE=SC-2,FS=80
NODE=SC-2,DIORead=30
NODE=SC-2,DIOWrite=40
NODE=SC-2,NTX=30
NODE=SC-2,NRX=40

How can I parse the file and create a dictionary for node SC-1 and one for node SC-2 that I can later in my program refer to to get specific values for specific nodes?

Upvotes: 2

Views: 3214

Answers (5)

Sufian Latif
Sufian Latif

Reputation: 13356

You can create a "2D" dictionary, i.e. a dictionary of dictionaries.

The keys of the "outer" dictionary will be the node names (e.g. 'SC-1', 'SC-2'), and the value will be another dictionary with keys {CPU, MEM, FS, DIORead, DIOWrite, NTX, NRX}.

like this:

outerDict = {}
for line in open('input', 'rb').readlines():
    key = line.split(',')[0].split('=')[0]
    key2, val = line.split(',')[1].split('=')

    if outerDict.has_key(key):
        outerDict[key][key2] = val
    else:
        outerDict[key] = {}
        outerDict[key][key2] = val

Upvotes: 0

ronakg
ronakg

Reputation: 4212

Considering your file structure is consistent with your example above, this is what I'd do -

import pprint

def read_file_into_dict(filename):
    f = open(filename, 'r')

    main_dict = {}

    for line in f:
        line = line.strip()
        node_line, param_line = line.split(',')
        node_name = node_line.split('=')[1]
        param, value = param_line.split('=')

        if main_dict.get(node_name):
            main_dict[node_name][param] = value
        else:
            main_dict[node_name] = {param: value}

    return main_dict

pprint.pprint(read_file_into_dict('sample.txt'))

Here's the output -

$ python sample.py 
{'SC-1': {'CPU': '90',
          'DIORead': '30',
          'DIOWrite': '40',
          'FS': '80',
          'MEM': '10',
          'NRX': '40',
          'NTX': '30'},
 'SC-2': {'CPU': '80',
          'DIORead': '30',
          'DIOWrite': '40',
          'FS': '80',
          'MEM': '10',
          'NRX': '40',
          'NTX': '30'}}

Upvotes: 0

Dan D.
Dan D.

Reputation: 74685

from collections import defaultdict
d = defaultdict(dict)
for line in open('input_file','r'):
    line = line.strip()
    a,b = line.split(',')
    node = a.split('=')[1] 
    key, value = b.split('=')
    d[node][key] = value

Upvotes: 4

sje397
sje397

Reputation: 41862

Here's my try (untested):

sc1 = {}    
sc2 = {}    
f = open("myfile", "r")
for line in f:  
  dict = None
  for statement in line.split(','):
    varname, value = statement.split('=')
    if varname == 'NODE' and value == 'SC-1':
      dict = sc1
    elif varname == 'NODE' and value == 'SC-2':
      dict = sc2
    else:
      dict[varname] = value

Upvotes: 0

Srikar Appalaraju
Srikar Appalaraju

Reputation: 73698

I believe you want to parse this file & keep all SC-* as keys and the rest of the stuff as their values. If the keys are duplicates, then merge the values. If this is what you are looking for, then i have hand-written some code which does exactly that -

I split the line first on , then on = & get the key, if key already there then merge else create a new entry.

def readFileIntoDict(fileHandle, dictName):
     line = fileHandle.readline() 
     dictName = {} 

     while line: 
         key  = line.split(',').split('=')[1]
         if key in dictName:
             dictName[key].append(line)
         else:
             dictName[key] = [line]
         line = fileHandle.readline() 
     return dictName

Correct me if i have interpreted what you want.

Upvotes: 0

Related Questions