简体   繁体   中英

writing data to csv from dictionaries with multiple values per key

Background

I am storing data in dictionaries. The dictionaries can be off different length and in a particular dictionary there could be keys with multiple values. I am trying to spit out the data on a CSV file.

Problem/Solution

Image 1 is how my actual output prints out. Image 2 shows how i would want my output to actually printout. Image 2 is the desired output .

在此处输入图片说明 在此处输入图片说明

CODE

import csv
from itertools import izip_longest

e = {'Lebron':[25,10],'Ray':[40,15]}
c = {'Nba':5000}

def writeData():
    with open('file1.csv', mode='w') as csv_file:
        fieldnames = ['Player Name','Points','Assist','Company','Total Employes']
        writer = csv.writer(csv_file)
        writer.writerow(fieldnames)

        for employee, company in izip_longest(e.items(), c.items()):
            row = list(employee)
            row += list(company) if company is not None else ['', '']  # Write empty fields if no company

            writer.writerow(row)

writeData()

I am open to all solutions/suggestions that can help me get my desired output format.

from collections import defaultdict

values = defaultdict(dict)
values[Name1] = {Points: [], Assist: [], Company: blah, Total_Employees: 123}

for generating the output, traverse through each item in the values to give you names, and populate other values using the key_values in the nested dict.

Again, make sure that there no multiple entries with same name, or choose the one with unique entries in the defaultdict.

Demo for the example-

>>> from collections import defaultdict
>>> import csv
>>> values = defaultdict(dict)
>>> vals = [["Lebron", 25, 10, "Nba", 5000], ["Ray", 40, 15]]
>>> fields = ["Name", "Points", "Assist", "Company", "Total Employes"]
>>> for item in vals:
...     if len(item) == len(fields):
...             details = dict()
...             for j in range(1, len(fields)):
...                     details[fields[j]] = item[j]
...             values[item[0]] = details
...     elif len(item) < len(fields):
...             details = dict()
...             for j in range(1, len(fields)):
...                     if j+1 <= len(item):
...                             details[fields[j]] = item[j]
...                     else:
...                             details[fields[j]] = ""
...             values[item[0]] = details
... 
>>> values
defaultdict(<class 'dict'>, {'Lebron': {'Points': 25, 'Assist': 10, 'Company': 'Nba', 'Total Employes': 5000}, 'Ray': {'Points': 40, 'Assist': 15, 'Company': '', 'Total Employes': ''}})
>>> csv_file =  open('file1.csv', 'w')
>>> writer = csv.writer(csv_file)
>>> for i in values:
...     row = [i]
...     for j in values[i]:
...             row.append(values[i][j])
...     writer.writerow(row)
... 
23
13
>>> csv_file.close()

Contents of 'file1.csv':

Lebron,25,10,Nba,5000
Ray,40,15,,

For a much simpler answer, you just need to add one line of code to what you have:

row = [row[0]] + row[1]

so:

for employee, company in izip_longest(e.items(), c.items()):
        row = list(employee)
        row = [row[0]] + row[1]
        row += list(company) if company is not None else ['', '']  # Write empty fields if no company

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