简体   繁体   English

python字典与元组列表到CSV

[英]python dictionary with list of tuples to CSV

How can a python dictionary that looks like this: 如何看起来像这样的python字典:

{
    'RCLS1': [(0, 20),  (10, 112),  (20, 130), (30, 102)],
    'RCLS2': [(0, 16),(10, 53),(20, 96), (30, 45)]
}

be converted to a CSV with structure: 转换为具有以下结构的CSV:

RCLS1,  0,  20
RCLS1, 10, 112
.
.
.
RLCS2, 30,  45

I have tried this: 我试过这个:

with open(r'E:\data.csv', "wb") as f:
    csv.writer(f).writerows((k,) + v for k, v in dct.items())

but this resulted in the following error: 但是这导致了以下错误:

can only concatenate tuple (not "list") to tuple

Based on the sample input/output you provided, you can iterate through the dictionary's key-value pairs, then iterate through the list of tuple values associated with each key, build the associated CSV row string, and write it to the CSV file, like so: 根据您提供的示例输入/输出,您可以遍历字典的键值对,然后遍历与每个键关联的元组值列表,构建关联的CSV行字符串,并将其写入CSV文件,如所以:

dct = {'RCLS1':[(0, 20),  (10, 112),  (20, 130), (30, 102)], 'RCLS2': [(0, 16),(10, 53),(20, 96), (30, 45)]}
int_to_str = lambda int_value: str(int_value)

with open(r"data.csv", "w") as csv_file:
    for key, values in dct.items():
         for tuple_value in values:
             csv_row = [key] + list(map(int_to_str, list(tuple_value)))
             csv_file.write(", ".join(csv_row) + "\n")

data.csv results: data.csv结果:

RCLS2, 0, 16
RCLS2, 10, 53
RCLS2, 20, 96
RCLS2, 30, 45
RCLS1, 0, 20
RCLS1, 10, 112
RCLS1, 20, 130
RCLS1, 30, 102

If what i understood from your question is correct, your are trying to do something like this (without the need to use of csv module): 如果我从你的问题中理解的是正确的,那么你正在尝试做这样的事情(不需要使用csv模块):

a = {'RCLS1':[(0, 20),  (10, 112),  (20, 130), (30, 102)], 'RCLS2': [(0, 16),(10, 53),(20, 96), (30, 45)]}

with open('E:\data.csv', 'a+') as f:
    for k,v in a.items():
        f.write("{0}: {1}\n".format(k,", ".join(", ".join(str(j) for j in k) for k in v)))

Output (The date in your file will be similar to this output): 输出(文件中的日期与此输出类似):

RCLS1: 0, 20, 10, 112, 20, 130, 30, 102
RCLS2: 0, 16, 10, 53, 20, 96, 30, 45

Otherwise, if you want to have the data by pair you can do something like this: 否则,如果您想要成对拥有数据,您可以执行以下操作:

with open('E:\data.csv', 'a+') as f:
    for k,v in a.items():
        f.write("{0}: {1}\n".format(k, "".join(", ".join(str(k) for k in v))))

Output: 输出:

RCLS1: (0, 20), (10, 112), (20, 130), (30, 102)
RCLS2: (0, 16), (10, 53), (20, 96), (30, 45)

Edit: 编辑:

A quick solution to your new update. 快速解决您的新更新。 You can do something like this: 你可以这样做:

a = {'RCLS1':[(0, 20),  (10, 112),  (20, 130), (30, 102)], 'RCLS2': [(0, 16),(10, 53),(20, 96), (30, 45)]}

with open('E:\data.csv', 'a+') as f:
    for k,v in a.items():
        for j in v:
            f.write("{0}: {1}\n".format(k, ", ".join(str(k) for k in j)))

Output: 输出:

RCLS2: 0, 16
RCLS2: 10, 53
RCLS2: 20, 96
RCLS2: 30, 45
RCLS1: 0, 20
RCLS1: 10, 112
RCLS1: 20, 130
RCLS1: 30, 102

one alternative answer using pandas : 使用pandas一个替代答案:

>>> import pandas as pd
>>> d={'RCLS1':[(0, 20),  (10, 112),  (20, 130), (30, 102)], 'RCLS2': [(0, 16),(10, 53),(20, 96), (30, 45)]}
>>> df=pd.DataFrame(d)


       RCLS1     RCLS2
0    (0, 20)   (0, 16)
1  (10, 112)  (10, 53)
2  (20, 130)  (20, 96)
3  (30, 102)  (30, 45)
[4 rows x 2 columns]

>>> dfs=df.stack().reset_index(level=0)

       level_0          0
RCLS1        0    (0, 20)
RCLS2        0    (0, 16)
RCLS1        1  (10, 112)
RCLS2        1   (10, 53)
RCLS1        2  (20, 130)
RCLS2        2   (20, 96)
RCLS1        3  (30, 102)
RCLS2        3   (30, 45)


>>> dfs=dfs[0].apply(pd.Series)  # break the tuples in column with "name"=0

        0    1
RCLS1   0   20
RCLS2   0   16
RCLS1  10  112
RCLS2  10   53
RCLS1  20  130
RCLS2  20   96
RCLS1  30  102
RCLS2  30   45


>>> dfs.to_csv('fileName.csv')

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM