简体   繁体   English

Python:将字典打印到csv,每个键值都换行

[英]Python: print dictionary to csv, each key value in a new line

I have the following data 我有以下数据

{'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['A', 'C'], ['B', 'C'], ['A', 'B']]}

and I want to print it to a csv file as following: 并且我想将其打印到csv文件,如下所示:

index   similar  markets
1       [0,2]   ['A','C']
2       [1,2]   ['B','C']
3       [2,1]   ['A','B']

currently my code is as following: 目前我的代码如下:

with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
    w = csv.DictWriter(f, a.keys())
    w.writeheader()
    w.writerow(a)

and it prints: 它打印:

 index               similair                       markets
[1, 2, 3]   [[0, 2], [1, 2], [2, 1]]    [['A', 'C'], ['B', 'C'], ['A', 'B']]
import csv

a = {'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['A', 'C'], ['B', 'C'], ['A', 'B']]}
keys = ['index', 'similar', 'markets']

with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
    w = csv.writer(f)
    w.writerow(keys)
    w.writerows(zip(*[a[key] for key in keys]))

CSV file: CSV档案:

index,similar,markets
1,"[0, 2]","['A', 'C']"
2,"[1, 2]","['B', 'C']"
3,"[2, 1]","['A', 'B']"

you can use the pandas library: 您可以使用pandas库:

import pandas as pd

x = {'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['A', 'C'], ['B', 'C'], ['A', 'B']]}

x = pd.DataFrame(x)
x.to_csv('mycsvfile.csv', index = False)

the csv will be: csv将是:

index,markets,similar
1,"['A', 'C']","[0, 2]"
2,"['B', 'C']","[1, 2]"
3,"['A', 'B']","[2, 1]"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使字典的每个键值在新行上打印? - how to make each key-value of a dictionary print on a new line? Python Print字典键,值是列表时的值。 在单独的行上打印每个键,值 - Python Print dictionary key, value when value is a list. Print each key, value on seperate line 在新行上为字典中的每个键输出多个值,并在键之前 - print multiple values for each key in a dictionary on a new line, preceded by the key Python:当一个键有多个值时,如何将字典写入csv文件,每个键是一个新行,但每个值是一个新列? - Python: How to write dictionary to csv file when one key has multiple values, each key is a new row, but each value is a new column? Python,如何在每一行中打印字典键及其值? - Python, how to print dictionary key and its values in each line? Python:当每个键和值都在新行上时,如何将文本文件读入字典? - Python: How to read a text file into a dictionary when each key and value is on a new line? 如何从 Python 字典中的每个键打印一个特定值? - How to print one specific value from each key in a dictionary in Python? 如何为字典中的新行打印 1 个值,其中包含 python 中的 2 个值? - How to print 1 value for a new line from dictionary contains 2 values in python? 将每个字典值与 csv 列条目匹配并将字典键应用于新列 - Match each dictionary value with csv column entry and apply dictionary key to new column 如何在嵌套字典的新行中打印每个较小的字典 - How print each smaller dictionary in new line in nested dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM