【问题标题】:Python dictionary keys to csv file with column match具有列匹配的 csv 文件的 Python 字典键
【发布时间】:2016-01-28 20:49:09
【问题描述】:

我正在尝试通过将键与 csv 标题中的列相匹配,将多个字典(键和值)推送到 csv 文件。 示例:

import csv
d1 = {'a':1, 'b':2, 'c': 3}
d2 = {'d':4, 'e':5, 'f': 6}
with open('my_data.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(['a', 'b', 'c', 'd', 'e', 'f'])

#iterate through all keys in d1,d2,dn
#if key matches column:
    #write value of key to the bottom of column
#else:
    #error key not found in header

mydata.csv 中的预期结果

a,b,c,d,e,f
1,2,3,4,5,6

【问题讨论】:

  • 不确定我明白了。您是否将所有 dicts 合并到输出文件中的一行中(如图所示)?还是您希望每个输入字典成为输出文件中的一行?

标签: python parsing csv dictionary


【解决方案1】:

答案是.. 不要只将列名传递给 writerow().. 将它们放在变量 columns 中,然后使用它来控制写出值的顺序。 Python 字典没有顺序。您必须使用一点代码将值排序为您想要的顺序。

将值写入 CSV 的最后一行代码使用名为 List Comprehension 的 Python 功能。这是一个节省 3-4 行代码的快捷方式。查一下,它们非常好用。

import csv
d1 = {'a':1, 'b':2, 'c': 3}
d2 = {'d':4, 'e':5, 'f': 6}

columns = ['a', 'b', 'c', 'd', 'e', 'f']

# combine d1 and d2 into data.. there are other ways but this is easy to understand
data = dict(d1)
data.update(d2)

with open('my_data.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(columns)
    # make a list of values in the order of columns and write them
    w.writerow([data.get(col, None) for col in columns])

这是没有列表理解的情况:

    row = []
    for col in columns:
        row.append(data.get(col, None)) 
    w.writerow(row)

【讨论】:

    猜你喜欢
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 2021-01-10
    • 2014-10-03
    • 2022-10-14
    • 2018-11-10
    • 1970-01-01
    相关资源
    最近更新 更多