【问题标题】:writing data to csv from dictionaries with multiple values per key从每个键具有多个值的字典中将数据写入 csv
【发布时间】:2018-10-26 16:56:14
【问题描述】:

背景

我将数据存储在字典中。字典可以有不同的长度,并且在特定的字典中可能有具有多个值的键。我正在尝试将数据吐出 CSV 文件。

问题/解决方案

图 1 是我的实际输出如何打印出来的。图 2 显示了我希望我的输出如何实际打印输出。 图像 2 是所需的输出

代码

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()

我愿意接受所有可以帮助我获得所需输出格式的解决方案/建议。

【问题讨论】:

  • q 回答了吗?

标签: python csv import-csv izip


【解决方案1】:

要获得更简单的答案,您只需在已有的代码中添加一行代码:

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

所以:

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}
    

    为了生成输出,遍历值中的每个项目以提供名称,并使用嵌套字典中的 key_values 填充其他值。

    再次,确保没有多个具有相同名称的条目,或者在 defaultdict 中选择具有唯一条目的条目。

    示例演示-

    >>> 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()
    

    'file1.csv' 的内容:

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

    【讨论】:

    • 可以演示一下吗?
    猜你喜欢
    • 2021-06-15
    • 2015-07-25
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 2019-07-02
    • 2016-10-27
    • 2023-03-16
    • 2016-12-10
    相关资源
    最近更新 更多