列表字典列表

时间:2014-06-02 19:34:14

标签: python dictionary

我无法将字典列表转换为列表字典。任何指导和帮助表示赞赏。我的CSVreader是词典列表。打印时,它会提供一个巨大的词典列表,我希望它是一个列表字典。这是我正在谈论的CSVreader。

CSVreader = csv.DictReader(open( 'N:/Individual Files/Jerry/2013 customer list qc, cr, db, gb 9-19-2013_JerrysMessingWithVersion.csv', "rb"),dialect='excel', delimiter=',')

for row in CSVreader:
        print row 

2 个答案:

答案 0 :(得分:3)

假设您的CSVreader的行为类似于词典列表:

from collections import defaultdict
result = defaultdict(list)
for d in CSVreader:
    for k, v in d.items():
        result[k].append(v)

答案 1 :(得分:0)

在您的问题的评论中,您注意到输入数据是:

{'cust_no':126,'lastname':'smith','firstname':'john','cust_no:127','lastname':'s‌​moth','firstname','bob'}

请注意,这不是字典列表。这是:

[{ 'cust_no':126, 'lastname': 'smith', 'firstname':'john'}, {'cust_no':127, 'lastname':'smoth', 'firstname':'bob'}]

通过更正后的输入,您可以使用defaultdict获得所需内容。

>>> input_data = [{ 'cust_no':126, 'lastname': 'smith', 'firstname':'john'}, {'cust_no':127, 'lastname':'smoth', 'firstname':'bob'}]
>>> from collections import defaultdict
>>> output_data = defaultdict(list)
>>> for a_dict in input_data:
...     for k, v in a_dict.items():
...             output_data[k].append(v)
...
>>> output_data
defaultdict(<type 'list'>, {'lastname': ['smith', 'smoth'], 'cust_no': [126, 127], 'firstname': ['john', 'bob']})