user1182090
user1182090

Reputation: 301

when i try to append value in dict its showing key error

I have a css file of this type

col1    col2
AAA       
 a        1
  a1      1
  a2      1
 b        1
  b1      1
  b2      1

i am reading first col based on indentation,"AAA" has 0 no of spaces,"a" "b" has 1 space and "a1","a2" "b1" "b2" has 2 space, now i am printing dict as

d={'a':['a1','a2'],'b':['b1','b2']}

But what i want is

d={'AAA':['a','b'],'a':['a1','a2'],'b':['b1','b2']}

i am using code like this

reader=csv.DictReader(open("c:/Users/Darshan/Desktop/sss.csv"),dialect="excel")
for row in reader:
    a.append(row['col1'])
    for i in range(len(a)):
        if a[i].count(' ')==1:
            d[a[i]]=[]
            k=a[i]

        else a[i].count(' ')==2:
            d[k].append(a[i])

this print this output

 d={'a':['a1','a2'],'b':['b1','b2']}

so can anyone help me,thanks in advance

Upvotes: 0

Views: 2261

Answers (1)

machine yearning
machine yearning

Reputation: 10119

What if you just change your for loop to this:

# A variable to keep track of the least-nested level of your hierarchy
top_lvl = ''
k = ''
for i in range(len(a)):
    # Pre-compute this value so you don't have to do it twice or more
    c = a[i].count(' ')
    # This case is the topmost level
    if c == 0:
        top_lvl = a[i]
        d[top_lvl] = []
    # This case is the middle level
    elif c == 1:
        d[a[i]]=[]
        k=a[i]
        d[top_lvl].append(k)
    # This case is the most deeply nested level
    else: # c==2
        d[k].append(a[i])

In fact now that I'm making everything all sweet, you can probably just iterate through the values in a directly, without referring to its values by index. Like so:

# A variable to keep track of the least-nested level of your hierarchy
top_lvl = ''
# More descriptive variable names can make everything easier to read/understand
mid_lvl = ''
for val in a:
    # Pre-compute this value so you don't have to do it twice or more
    c = val.count(' ')
    # This case is the topmost level
    if c == 0:
        top_lvl = val
        d[val] = []
    # This case is the middle level
    elif c == 1:
        d[val]=[]
        mid_lvl =val
        d[top_lvl].append(mid_lvl)
    # This case is the most deeply nested level
    else: # c==2
        d[mid_lvl].append(val)

Upvotes: 3

Related Questions