【问题标题】:Pasting data from multiple dictionary into a csv // with python将多个字典中的数据粘贴到 csv // 使用 python
【发布时间】:2018-07-23 16:14:14
【问题描述】:

从今天早上开始,我一直在为下面的代码苦苦挣扎。我还是 python 的新手。我希望能够和你们一起帮助人们,但现在,我是新手。

我创建了一个带有静态变量的类产品来存储所有这些。

class Product(dict):
all_p=[]

def __init__(self):
    self['Nom'] = ','
    self['Marque'] = ','
    self['Description'] = ','
    self['Formule'] = ','

    all_p.append(self)

从我生成产品列表的循环中,我最终得到:

for i in range(0, len(all_p)):
    print(all_p[i])

我所有的产品。 (可能有更好的方法,但既然这样可行,我可以接受)。

这是我的产品列表示例:

[{'Nom': 'Mustard', 'Marque':'Heinz','Description','enjoy the meal!',
'Formule':['ingredient0','ingredient1','ingredient2','ingredient3','ingredient4']},
{'Nom': 'Ketchup', 'Marque':'Amora','Description','best with mussels',
'Formule':['ing0','ingredient1','ing2','ingredient3','ingredient4']}]

这是我真正的问题:

我想将此信息添加到名为myfile.csv 的csv 文件中,该文件位于C:\Users\myfolder,格式如下:

Col1            Col2                Col3                    ...
Nom             Mustard             Ketchup                 ...
Marque          Heinz               Amora                   ...
Description     enjoy the meal!     best with mussels       ...
formule         ['ingredient0',...] ['ing0',...]            ...

对不起,如果我太具体了。不应该太复杂,但是在解析 all_p[i] 并将信息添加到我的 Excel 时出现错误。 你的帮助会很棒!!

【问题讨论】:

    标签: python-3.x csv dictionary


    【解决方案1】:

    你可以试试下面的代码。

    在指定字段宽度时请小心。由于您的列表很长,因此这里静态采用 75

    details =[{'Nom': 'Mustard', 'Marque':'Heinz','Description': 'enjoy the meal!','Formule':['ingredient0','ingredient1','ingredient2','ingredient3','ingredient4']},{'Nom': 'Ketchup', 'Marque':'Amora','Description': 'best with mussels','Formule':['ing0','ingredient1','ing2','ingredient3','ingredient4']}]
    
    # print (details)
    
    d = {}
    for detail in details:
        for k, v in detail.items():
            if k in d:
                d[k].append(v)
            else:
                d[k] = [v]
    
    # print (d)
    # print(tuple("Col" + str(i) for i in range(1, len(d["Nom"])+2)) )
    if d:
        format_str =  "%-75s\t"*(len(d["Nom"])+1) 
        # print (format_str)
        s = format_str %tuple("Col" + str(i) for i in range(1, len(d["Nom"])+2)) + "\n"
    
    for k, v in d.items():
        s += format_str % (k, *v) + "\n"
    
    print (s)
    

    输出»

    Col1                                                                        Col2                                                                        Col3                                                                        
    Nom                                                                         Mustard                                                                     Ketchup                                                                     
    Description                                                                 enjoy the meal!                                                             best with mussels                                                           
    Formule                                                                     ['ingredient0', 'ingredient1', 'ingredient2', 'ingredient3', 'ingredient4'] ['ing0', 'ingredient1', 'ing2', 'ingredient3', 'ingredient4']               
    Marque                                                                      Heinz                                                                       Amora       
    

    最后,您可以使用以下代码将此字符串写入文件。

    with open("C:\\Users\\myfolder\\myfile.csv", "w", encoding="utf-8") as f:
        f.write(s)
    

    【讨论】:

    • 嗨@hygull,非常感谢。我得到一个“解析时意外的 EOF”,并在您的答案末尾使用 open 语句。这是因为我的用户名是带有口音的“Rémy”吗?
    • 是的@Madmaxoo,请使用with open("C:\\Users\\myfolder\\myfile.csv", "w", encoding="utf-8"),如果它解决了您的问题或遇到任何问题,请评论您的问题。
    【解决方案2】:

    首先将您的字典列表转换为 pandas DataFrame:

    import pandas as pd
    pd.DataFrame(all_p)
    

    然后您可以使用 pandas 将数据重新塑造成您想要的样子,最后使用 pandas 函数to_csv() 将 DataFrame 写入 CSV 文件。

    to_csv() 的文档是 here

    【讨论】:

    • 对不起,亚历克斯,但你的评论对我没有帮助。有人可以帮忙吗??
    猜你喜欢
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 2020-01-28
    • 2019-07-14
    • 2014-08-01
    • 1970-01-01
    相关资源
    最近更新 更多