将python字典放在csv的列表中

时间:2017-06-23 22:19:33

标签: python csv dictionary

我有一个包含字典的列表,其中包含该键的另一个列表。 我想将所有信息都放入csv中。我尝试了xlwtcsv,但我很难用它。

这是列表和dict,名为peopleFood

 {(170, '2017-05-31'): [[0, 3], [1, 2], [2, 3], [3, 1], [4, 2], [5, 1], [6, 2], [7, 
 3], [8, 6], [9, 8], [10, 9], [11, 10], [12, 9], [13, 9], [14, 6], [15, 8], [16, 
 7], [17, 3], [18, 3], [19, 3], [20, 2], [21, 1], [22, 1], [23, 1]]},
 {(176, '2017-05-23'): [[14, 9], [13, 9], [17, 5], [10, 10], [20, 2], [8, 5], [16, 7], [7, 4], [6, 1], [5, 2], [11, 11], [1, 2], [15, 9], [21, 3], [4, 1], [3, 2], [22, 3], [23, 3], [12, 10], [2, 1], [18, 2], [19, 2], [9, 12], [0, 2]]}, 
{(152, '2017-05-31'): [[0, 3], [1, 2], [2, 3], [3, 1], [4, 2], [5, 1], [6, 2], [7, 3], [8, 6], [9, 8], [10, 9], [11, 10], [12, 9], [13, 9], [14, 6], [15, 8], [16, 7], [17, 3], [18, 3], [19, 3], [20, 2], [21, 1], [22, 1], [23, 1]]}

我不会粘贴代码,因为它几乎都不起作用。我尝试在其他问题中查看How do I write a Python dictionary to a csv file,但列表中的字典会弄乱代码。

2 个答案:

答案 0 :(得分:1)

这在Python方面相对容易。使用您的数据:

data = [
    {(170, '2017-05-31'): [
        [0, 3], [1, 2], [2, 3], [3, 1], [4, 2], [5, 1], [6, 2], [7, 3], [8, 6], [9, 8],
        [10, 9], [11, 10], [12, 9], [13, 9], [14, 6], [15, 8], [16, 7], [17, 3], [18, 3],
        [19, 3],[20, 2], [21, 1], [22, 1], [23, 1]
    ]},
    {(176, '2017-05-23'): [
        [14, 9], [13, 9], [17, 5], [10, 10], [20, 2], [8, 5], [16, 7], [7, 4], [6, 1],
        [5, 2], [11, 11], [1, 2], [15, 9], [21, 3], [4, 1], [3, 2], [22, 3], [23, 3],
        [12, 10], [2, 1], [18, 2], [19, 2], [9, 12], [0, 2]
    ]},
    {(152, '2017-05-31'): [
        [0, 3], [1, 2], [2, 3], [3, 1], [4, 2], [5, 1], [6, 2], [7, 3], [8, 6], [9, 8],
        [10, 9], [11, 10], [12, 9], [13, 9], [14, 6], [15, 8], [16, 7], [17, 3], [18, 3],
        [19, 3], [20, 2], [21, 1], [22, 1], [23, 1]
    ]}
]

您需要做的就是:

with open("test.csv", "wb") as f:  # on Python 3.x use "w" mode and newline='' instead
    writer = csv.writer(f)
    for category in data:  # get our category
        for header, rows in category.iteritems():  # use category.items() on Python 3.x
            writer.writerow(header)  # add the category/date header
            writer.writerow(["People", "Food"])  # add the mandatory sub-header
            writer.writerows(rows)  # write the rest of the data

获取您的CSV ...但是加载此类CSV是另一个主题。

答案 1 :(得分:0)

with open('filename', 'w') as buffer:
    data = [{(...): [...]}, {...}, ...]

    keys = ('people', 'food')

    writer = csv.DictWriter(buffer, fieldnames=keys)

    for record in data:
        first_row = {i: '' for i in record.keys()}
        writer.writerow(first_row)
        writer.writeheader()
        rows = [dict(zip(keys, row)) for row in record.items()[0]]
        writer.writerows(rows)