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

Question:

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
Asked By: Max

||

Answers:

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.

Answered By: ddejohn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.