将包含多个项目和值的字典写入cvs文件

时间:2017-07-08 00:15:15

标签: python csv dictionary

我有一个包含多个键和值的字典,如下所示:

 My_data = {'key1': [item1 value1, item2 value2],
            'key2': [item1 value1, item2 value2],
            'key3': [item1 value1, item2 value2]}

现在,我需要将它们写入csv文件,如下所示:

      Item1    Item2   Item3

Key1  value1   value2 value3
Key2  value1   value2 value3
Key3  value1   value2 value3

有人知道怎么做吗?我尝试了这段代码但不起作用:

with open("dict2csv.csv", 'wb') as csv_file:
    for key, value in My_data.items():      
        csv_file.write('%s:%s\n' % (key, value))

1 个答案:

答案 0 :(得分:1)

如果您正确地将My_data格式化为具有有效键值对的字典,并且该值是有效元组或列表,则这是获得所需输出的方法之一。 (假设该值将是(item,value)的元组)。

如果您的项目和值是两个单词,那么您可以选择方法2.

这是基本编码,您必须添加错误处理和其他化妆品,以使其非常适合您的输入验证。

import platform

## Approach 1
My_data = {'key1': [('item1','value1'),('item2','value2')], 'key2': [('item1','value1'), ('item2','value2')], 'key3': [('item1','value1'), ('item2','value2'), ('item3','value3')]}

print("Python version : " + platform.python_version())

print()

print("Approach 1 with formatted My_data")
with open("dict2csv1.csv", 'w') as output:
    ## print data
    for key, values in My_data.items():
        data = ""
        for value in values:
            data = data + value[1] + ","
        data = key + "," + data[:-1] + "\n"
        ## display on console for debugging
        print(data, end='')
        output.write(data)

print()

## Approach 2    
print("Approach 2 with given My_data")
My_data = {'key1': ['item1 value1', 'item2 value2'], 'key2': ['item1 value1', 'item2 value2'], 'key3': ['item1 value1', 'item2 value2', 'item3 value3']}
with open("dict2csv2.csv", 'w') as output:
    ## print data
    for key, values in My_data.items():
        data = ""
        for value in values:
            valueItems = value.split()
            data = data + valueItems[1] + ","
        data = key + "," + data[:-1] + "\n"
        ## display on console for debugging
        print(data, end='')
        output.write(data)

示例运行(key3有超过2个项目,即每个键具有不同数量的项目)

Python version : 3.6.1

Approach 1 with formatted My_data
key1,value1,value2
key2,value1,value2
key3,value1,value2,value3

Approach 2 with given My_data
key1,value1,value2
key2,value1,value2
key3,value1,value2,value3