NutshellProgrammer NutshellProgrammer - 4 months ago 9
Python Question

Dictionary to list with lists inside and print to csv

I have a dictionary I wish to turn into a list containing lists so that I can write into a csv, but what ever I do, it doesn't work.

I used sorted(dllist.items()) to sort them as

[(key1, value1), (key2, value2), ... ,(keyN, valueN)]


This is what I have,

dict = [('aaa', [5787, 40, 1161, 1222]),
('aab', [6103, 69, 810, 907]),
('aac', [3081, 41, 559, 638]),
('aae', [1011000, 191, 411, 430])]


I want it to be

list = [(aaa, 5787, 40, 1161, 1222),
('aab',6103, 69, 810, 907),
('aac', 3081, 41, 559, 638),
('aae', 1011000, 191, 411, 430)]


What am doing wrong? and how do I do it easiest to store it in a csv as a row for each element?

Answer

Given my assumption about what your dictionary looks like, this should do the conversion you want and write the output to a CSV file:

import csv

d = { 'aaa': [5787, 40, 1161, 1222], 'aab': [6103, 69, 810, 907] }
rows = [[k] + v for k, v in sorted(d.items())]

with open("out.csv", "w") as out:
    writer = csv.writer(out)
    for row in rows:
        writer.writerow(row)

# out.csv:
# aaa,5787,40,1161,1222
# aab,6103,69,810,907