从元组列表的字典创建CSV文件

时间:2016-04-25 20:27:11

标签: python csv dictionary tuples

我想拿这本词典:

    table = {2015-11-10:[('pear', 22), ('banana', 50)], 
    2015-11-13:[('banana', 22), ('apple', 50), ('strawberry', 30), ('pear', 35), ('orange', 2), ('mango', 76)]
    2015-11-12:[('banana', 22), ('orange', 50), ('mango', 30), ('strawberry', 35)]
    }

    with open ('transaction.csv', 'wb') as f:
        w = csv.writer(f, delimiter = ',')
        w.writerow(['transaction_date', 'fruits', 'quantity'])
        for k,v in table.items():
            w.writerow([k,v])

我想要打印的是每个键,即日期只有一对元组,只有三列。 但是我一直打印出来:

    2015-11-10,"[('pear', 22), ('banana', 50)]"
    2015-11-13,"[('banana', 22), ('apple', 50), ('strawberry', 30), ('pear', 35), ('orange', 2), ('mango', 76)]"
    2015-11-12,"[('banana', 22), ('orange', 50), ('mango', 30), ('strawberry', 35)]"

而不是:

    2015-11-10,pear,22
    2015-11-10,banana,50
    2015-11-13,banana,22

等等。

任何帮助肯定会受到赞赏。谢谢。

2 个答案:

答案 0 :(得分:3)

数据结构是嵌套的。你需要一个内循环而不是水果和数量:

import csv

table = {"2015-11-10": [('pear', 22), ('banana', 50)],
         "2015-11-13": [('banana', 22), ('apple', 50), ('strawberry', 30), ('pear', 35), ('orange', 2), ('mango', 76)],
         "2015-11-12": [('banana', 22), ('orange', 50), ('mango', 30), ('strawberry', 35)]
         }

with open('transaction.csv', 'wb') as f:
    w = csv.writer(f, delimiter=',')
    w.writerow(['transaction_date', 'fruits', 'quantity'])

    for transaction_date, fruits in table.items():
        for fruit, quantity in fruits:
            w.writerow([transaction_date, fruit, quantity])

以下是运行代码后transaction.csv内的内容:

transaction_date,fruits,quantity
2015-11-10,pear,22
2015-11-10,banana,50
2015-11-13,banana,22
2015-11-13,apple,50
2015-11-13,strawberry,30
2015-11-13,pear,35
2015-11-13,orange,2
2015-11-13,mango,76
2015-11-12,banana,22
2015-11-12,orange,50
2015-11-12,mango,30
2015-11-12,strawberry,35

答案 1 :(得分:0)

我认为这将实现您的目标。您还需要迭代与每个日期键关联的值对:

import csv

table = {
    '2015-11-10':[('pear', 22),
                  ('banana', 50)], 
    '2015-11-13':[('banana', 22),
                  ('apple', 50),
                  ('strawberry', 30),
                  ('pear', 35),
                  ('orange', 2),
                  ('mango', 76)],
    '2015-11-12':[('banana', 22),
                  ('orange', 50),
                  ('mango', 30),
                  ('strawberry', 35)]
    }

with open ('transaction.csv', 'wb') as f:
        w = csv.writer(f, delimiter = ',')
        w.writerow(['transaction_date', 'fruits', 'quantity'])
        for date, pairs in table.items():
            for pair in pairs:
                w.writerow([date, pair[0], pair[1]])