简体   繁体   中英

list of dictionaries to dictionary of lists

I'm having trouble converting a list of dictionaries into a dictionary of lists. Any guidance and help is appreciated. My CSVreader is the list of dictionaries. When printed, it gives a HUGE list of dictionaries, and I'd like that to be a dictionary of lists. Here is the CSVreader I'm talking about.

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 

Assuming your CSVreader behaves like a list of dictionaries:

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

In the comments to your question you noted that the input data is:

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

Note that this is not a list of dictionaries. This, is:

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

Going by the corrected input, you can get what you want using 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']})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM