python - 如何将字典以某种格式写入文件

标签 python python-3.x dictionary

假设我有多个字典列表,类似于

list_one = [{'genre': 'Action', 'amount': 141, 'meanScore': 82}, {'genre': 'Comedy', 'amount': 191, 'meanScore': 82}]

list_two = [{'genre': 'Horror', 'amount': 11, 'meanScore': 62}, {'genre': 'Comedy', 'amount': 191, 'meanScore': 82}]

我的目标是将其写入表单中的文件

           Action       Comedy       Horror      
list_one  meanScore   meanScore    
           amount       amount       
list_two              meanScore     meanScore
                        amount       amount

我不太熟悉 dict 以及存储它们的最佳方法是什么,但 csv 文件似乎很受欢迎。我尝试使用 this answer here来解决我的问题,但我很难理解@MarkLongair 的作用以及如何将其扩展到我的问题。我关心的主要事情之一是,并非每个流派都是每个列表的一部分,因此我不知道如何检查现有的 csv 文件是否存在 key 、它位于何处以及如何将值写入右栏。

由于我无法真正理解链接的答案,所以我尝试了类似的内容

from pandas import DataFrame

list_one = [{'genre': 'Action', 'amount': 141, 'meanScore': 82},
            {'genre': 'Comedy', 'amount': 191, 'meanScore': 82}]

list_two = [{'genre': 'Horror', 'amount': 11, 'meanScore': 62}, 
            {'genre': 'Comedy', 'amount': 191, 'meanScore': 82}]

DataFrame(list_one).to_csv('test.csv')
DataFrame(list_two).to_csv('test.csv')

这并没有真正起作用,因为数据被覆盖并且我想要的列被转换为行......

我不知道如何继续这里的表格或到底什么是正确的方向...有人可以帮忙吗?

最佳答案

在不使用 Pandas 的情况下解决这个问题的一种方法是创建一个函数来查看您的一本字典,并组成适当的 CSV 文本行。

def generate_row(separator, headers, data_type, data_list, list_name):
    data_by_genre = {k: '' for k in headers}
    for data in data_list:
        data_by_genre[data['genre']] = str(data[data_type])

    output_text = separator.join([data_by_genre[genre] for genre in headers]) + '\n'
    # If it's 'amount', then the row starts with the name. Otherwise that space is blank.
    if data_type == 'amount':
        output_text = list_name + output_text

    return output_text


list_one = [{'genre': 'Action', 'amount': 141, 'meanScore': 82}, {'genre': 'Comedy', 'amount': 191, 'meanScore': 82}]
list_two = [{'genre': 'Horror', 'amount': 11, 'meanScore': 62}, {'genre': 'Comedy', 'amount': 191, 'meanScore': 82}]

headers = ['', 'Action', 'Comedy', 'Horror']
separator = ','

f = open('new.csv', 'w')
f.write(separator.join(headers))
f.write('\n')
f.write(generate_row(separator, headers, 'amount', list_one, 'list_one'))
f.write(generate_row(separator, headers, 'meanScore', list_one, 'list_one'))
f.write(generate_row(separator, headers, 'amount', list_two, 'list_two'))
f.write(generate_row(separator, headers, 'meanScore', list_two, 'list_two'))
f.close()

我将“分隔符”设置为变量,以防您想使用例如制表符分隔而不是逗号。

如果你想使用 Pandas,你可以编写一些东西来重新格式化你的数据,使其看起来像这样,这样它就会“正确”地写入。

data1 = [{'Action': 141, 'Comedy': 191, 'Horror': None},
         {'Action': 82, 'Comedy': 82, 'Horror': None},
         {'Action': None, 'Comedy': 191, 'Horror': 11},
         {'Action': None, 'Comedy': 82, 'Horror': 62}]

DataFrame(data1).to_csv('test.csv')

关于python - 如何将字典以某种格式写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53877012/

相关文章:

python - 将 static() 添加到 urlpatterns 只能通过附加到列表来工作

python - 为每个值复制 python 字典

python - 将列表列表中的特定元素从字符串转换为整数

python - Python for循环中发生的内部操作

python matplotlib 以小时格式设置 xticks

python - Windows 上的错误 "Import Error: No module named numpy"

python - 创建一个空字典,键是可变维度的元组

C++ 函数映射

python正则表达式在字符的最后两次出现之间保留文本

python - 检查日期时间字符串是否为 ISO 8601 格式