将默认字典嵌套在默认字典中

时间:2016-02-29 19:14:23

标签: python csv dictionary defaultdict

我正在尝试读取格式化的csv

Number,Letter,Color,
1,a,blue,
1,b,green,
1,c,yellow, 

然后拿出像这样的嵌套词典

{
"1":[
    "Letter":["a","b","c"],
    "Color":["blue","green","yellow"]
    ]
}

我可以从csv中获取Number及其相关的行,但是一旦我尝试嵌套,我就会得到AttributeError:' collections.defaultdict'对象没有属性'追加',我认为我大部分是在正确的开始

result = co.defaultdict(lambda: co.defaultdict(list))
subresult = co.defaultdict(list)

with open(os.path.join(inputdir,tablelist[i])) as f:

    csv_reader = csv.reader(f)
    csv_headings = next(csv_reader)
    read = csv.DictReader(f, fieldnames=csv_headings)

    for line in read:
        subresult = {}
        for j in range(1,len(csv_headings)):
            #result[line[csv_headings[0]]].append(line[csv_headings[j]])
            result[line[csv_headings[0]]].append(subresult[csv_headings[j]].append(line[csv_headings[j]]))    

2 个答案:

答案 0 :(得分:2)

dict对象没有append方法而是使用update方法

类似的东西:

result[line[csv_headings[0]]].update(subresult[csv_headings[j]].append(line[csv_headings[j]]))

例如:

In [1]: a ={'a':1}

In [2]: a.append({'b':2})
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-02c9b6cd9396> in <module>()
----> 1 a.append({'b':2})

AttributeError: 'dict' object has no attribute 'append'

In [3]: a.update({'b':2})

In [3]: a
Out[3]: {'a': 1, 'b': 2}

答案 1 :(得分:2)

删除文件中的标题行,这有效:

from collections import defaultdict
d = defaultdict(lambda : defaultdict(list))
with open('myFile.txt', 'r') as f:
    for line in f:
        r = line.strip().split(",")
        number, letter, color = r[:3] 
        d[number]['Letter'].append(letter)
        d[number]['Color'].append(color)

print d

输出

defaultdict(<function <lambda> at 0x7f3d99f49b90>, {'1': defaultdict(<type 'list'>, 
{'Color': ['blue', 'green', 'yellow'], 'Letter': ['a', 'b', 'c']})})