简体   繁体   English

使用复合键从字典中写入 csv 文件

[英]Write a csv file from a dictionary with compound keys

I have a dictionary whose keys are tuples of 2 items.我有一本字典,其键是 2 个项目的元组。 I would like to write this dictionary as a .csv file.我想把这本字典写成.csv文件。

My dictionary counter looks like this:我的字典counter如下所示:

{("Banana", "Apple") : 1,
 ("Apple", "Pear") : 2,
 # ...
}

I've tried this:我试过这个:

header = ['group', 'list', 'id']
with open("file.csv", 'w') as f2:
    writer = csv.DictWriter(f2, fieldnames=header)
    writer.writeheader()
    for key, val in counter.items(): 
        write.writerow([key]+val)

But I get this error:但我得到这个错误:

TypeError: can only concatenate list (not "int") to list

Can somebody help me?有人可以帮助我吗?

Edit编辑

I've tried with this, too:我也试过这个:

with open("file.csv", 'w+') as f2:
    writer = csv.DictWriter(f2, fieldnames=header)
    writer.writeheader()
    for key, val in counter.items():
        writer.writerow(key,val)

But it now says:但它现在说:

TypeError: writerow() takes 2 positional arguments but 3 were given

From the sample of the contents of the counter dictionary you added, I now understand what you're trying to do.从您添加的counter字典的内容示例中,我现在了解您要做什么。

Here's how to accomplish what you want:以下是如何完成你想要的:

import csv

counter = {("Banana", "Apple"): 1,
           ("Apple", "Pear"): 2,
           # ...
          }

header = 'group', 'list', 'id'
with open("compound_keys.csv", 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writeheader()
    for (group, list_), id in counter.items():
        writer.writerow(dict(zip(header, (group, list_, id))))

Contents of .csv file created:创建的.csv文件的内容:

group,list,id
Banana,Apple,1
Apple,Pear,2

Note笔记

It would be simpler and more efficient in this case to use a csv.writer instead of a csv.DictWriter because then it wouldn't be nesssary to create a temporary dictionary to write each row of the output file (only a tuple).在这种情况下,使用csv.writer而不是csv.DictWriter会更简单、更有效,因为这样就不需要创建一个临时字典来写入 Z78E6221F6393D135DZ681DB3 文件的每一行(仅一个 14CE8 文件)。

The following produces exactly the same results:以下产生完全相同的结果:

header = 'group', 'list', 'id'
with open("compound_keys.csv", 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(header)
    for (group, list_), id in counter.items():
        writer.writerow((group, list_, id))

How about using the plain with open :如何使用普通with open

with open("file.csv", 'a+') as f:
    f.write('group' + ',' + 'list' + ',' + 'id'
    for key, value in f2.items():
        f.write(key[0] + ',' + key[1] + ',' + str(value))

As already mentioned by martineau , we can't really help without knowing what counter is, however, I think I see what's going wrong.正如martineau已经提到的,如果不知道counter是什么,我们就无法真正提供帮助,但是,我想我知道出了什么问题。

What you're saying is not possible.你说的不可能。 Every dictionary has an equal amount of keys as values, a key can't exist without a value.每个字典都有相同数量的键作为值,没有值就不能存在键。

From your question, I think this is what you're looking for:根据您的问题,我认为这就是您要寻找的:

header = ['group', 'list', 'id']
with open('file.csv', 'w+') as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writeheader()
    keys = list(counter.keys())
    values = list(counter.items())
    writer.writerow([keys[0], keys[1], values[0]])

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

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