Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CSV error AttributeError: 'int' object has no attribute 'keys'

I have this list of dict counters that I need to write in a csv, but I cannot figure out the problem.

t = Counter({'dog': 3, 'cat': 5})

with open('test.csv', 'w',encoding='utf8', newline="") as output_file:
    fieldnames = ["name", "count"]
    dict_writer = csv.DictWriter(output_file, fieldnames=fieldnames)
    dict_writer.writeheader()
    dict_writer.writerows(t)

Result:
wrong_fields = rowdict.keys() - self.fieldnames
AttributeError: 'int' object has no attribute 'keys'

What I want is a csv like this:

name,count
dog,3
cat,5

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

DictWriter takes a sequence of mappings each of which has to have the same keys as fieldnames — so you need [{"name": "dog", "count": 3}, ...]

To fix t:

rows = [{"name": name, "count": count} for name, count in t.items()]

And then pass rows to DictWriter.writerows(), or generate the correct data structure from the get-go.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading