简体   繁体   中英

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?

Given the output from sorted , this does it:

>>> my_dict = [('aaa', [5787, 40, 1161, 1222]), ('aab', [6103, 69, 810, 907]), ('aac', [3081, 41, 559, 638]), ('aae', [1011000, 191, 411, 430])]
>>> my_list = [tuple([i[0]] + i[1])  for i in my_dict]
>>>
>>> my_list
[('aaa', 5787, 40, 1161, 1222), ('aab', 6103, 69, 810, 907), ('aac', 3081, 41, 559, 638), ('aae', 1011000, 191, 411, 430)]

I have used my_list and my_dict in place of list and dict respectively to avoid shadowing the builtin names.

The code that does the trick:

[tuple([i[0]] + i[1])  for i in my_dict]
#      |<- put first item in a list
#               |<-  join with second item

puts the first item in each tuple in a list and concatenates with the second item in the tuple which is already a list. The operation is repeated on all tuples in a list comprehension.


Given a csv writer object, you can then use:

writer.writerows(my_list)

To write all the items into your csv file at a go.

You can add tuples (which appends them to each other) and you can convert lists into tuples. So, the following works for me:

>>> x = [('a', [1,2,3]), ('b', [4,5,6])]
>>> x
[('a', [1, 2, 3]), ('b', [4, 5, 6])]
>>> y = [(i,) + tuple(j) for i, j in x]
>>> y
[('a', 1, 2, 3), ('b', 4, 5, 6)]

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

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