writing data to csv from dictionaries with multiple values per key

不打扰是莪最后的温柔 提交于 2019-12-11 20:38:59

问题


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.


回答1:


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



回答2:


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,,


来源:https://stackoverflow.com/questions/53013274/writing-data-to-csv-from-dictionaries-with-multiple-values-per-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!