S
S
SymerDiff2021-07-11 00:51:31
Python
SymerDiff, 2021-07-11 00:51:31

How to add multiple dictionaries to CSV (Python)?

Converting a list to a dictionary using the Counter class, do I need to output everything to CSV? Here is the code that is there:

list1 = ['from=<[email protected]>', 'from=<[email protected]>', '[email protected]', '[email protected]', ]
list2 = ['to=<[email protected]>', 'to=<[email protected]>', 'to=<[email protected]>',  ]
countList1 = Counter(list1) 
countList2 = Counter(list2)

with open('outputTest.csv', 'w') as csvFile:
    writer = csv.writer(csvFile)
    header = ['email_from', 'quantity' 'email_to', 'quantity']
    writer.writerow(header)
    for item in countlister1:
        writer.writerow((item, counLister1[item]))  # Только для одного словаря

The output is a table (email, 10)
You need to add data from 3 dictionaries to the table. How can this be best done? Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
o5a, 2021-07-11
@SymerDiff

list1 = ['from=<[email protected]>', 'from=<[email protected]>', '[email protected]', '[email protected]', ]
list2 = ['to=<[email protected]>', 'to=<[email protected]>', 'to=<[email protected]>',  ]
# сформировать сколько нужно словарей по списку
counters = [Counter(x) for x in [list1, list2]]

with open('outputTest.csv', 'w') as csvFile:
    writer = csv.writer(csvFile)
    header = ['email_from', 'quantity' 'email_to', 'quantity']
    writer.writerow(header)
    for counter in counters:
        for item, cnt in counter.items():
            writer.writerow((item, cnt))

Or you can not initially create Counter, but do it already inside the lower loop.
Or you can initially add all the lists into one and do everything through a single Counter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question