当我尝试在dict中附加值时显示关键错误

时间:2012-03-29 09:27:01

标签: python dictionary

我有一个这种类型的css文件

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

我正在阅读基于缩进的第一个col,“AAA”有0个没有空格,“a”“b”有1个空格而“a1”,“a2”“b1”“b2”有2个空格,现在我我打印字典

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

但我想要的是

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

我正在使用像这样的代码

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])

这打印此输出

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

所以任何人都可以帮助我,提前谢谢

1 个答案:

答案 0 :(得分:3)

如果您只是将for循环更改为:

# 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])

事实上,现在我把所有东西都变得很甜蜜,你可以直接遍历a中的值,而不用索引来引用它的值。像这样:

# 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)