Creating a nested dictionary...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • GTXY20
    New Member
    • Oct 2007
    • 29

    Creating a nested dictionary...

    hello all,

    I have the following text file:

    1,a,good
    1,a,bad
    1,b,good
    1,c,bad

    would like to create a dictionary:

    Code:
    d={1:{'v1':(a,b,c), 'v2':(good)}}
    have been trying:

    Code:
    for line in lines:
        uh, tf, tp = line.split('%')
        if uh in d:
            f=d[uh]['v1']
            if tf not in f:
                f.append(tf)
            p=d[uh]['v2']
            if tp is not 'bad' and tp not in p:
                p.append(tp)
        else:
            d[uh]={'v1':[], 'v2':[]}
    unfortunately I keep getting where 'bad' is being appended to 'v2':

    Code:
    d={'1': {'v1': ['a', 'b', 'c'], 'v2': ['bad', 'good']}}
  • GTXY20
    New Member
    • Oct 2007
    • 29

    #2
    actually the code reads as follows but I am still having the same problem:

    Code:
    infile = open('input.txt', 'r')
    records = infile.read()
    infile.close()
    lines = records.split()
    d={}
    for line in lines:
        uh, tf, tp = line.split('%')
        if uh in d:
            f=d[uh]['v1']
            if tf not in f:
                f.append(tf)
            p=d[uh]['v2']
            if tp is not 'bad' and tp not in p:
                p.append(tp)
        else:
            d[uh]={'v1':[tf], 'v2':[tp]}

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      Originally posted by GTXY20
      unfortunately I keep getting where 'bad' is being appended to 'v2':

      Code:
      d={'1': {'v1': ['a', 'b', 'c'], 'v2': ['bad', 'good']}}
      I fail to see any logical reason that 'bad' would not be included in V2 since 'c' is in V1.

      Comment

      • GTXY20
        New Member
        • Oct 2007
        • 29

        #4
        Oh I understand, thanks.

        In order to remove these 'bad' entries I am thinkig of putting the follwing in after the dictionary is created to remove:

        Code:
        for key in d:
        	d[key]['v2'].remove('bad')

        Comment

        Working...