在计算机科学中将Python字典放入列表中

2024-09-27 17:55:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,里面有一本字典,里面还有一个键的列表。 我想把所有的信息放到一个csv中。我试过xlwtcsv,但我很难接受。你知道吗

这是一张单子和一张名为“人食”的单子

 {(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,但是列表中的dict把代码弄乱了。你知道吗


Tags: csvto代码信息列表dictionary字典粘贴
2条回答

这在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完全是另一个话题。你知道吗

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)

相关问题 更多 >

    热门问题