Home > front end >  CSV error AttributeError: 'int' object has no attribute 'keys'
CSV error AttributeError: 'int' object has no attribute 'keys'

Time:10-31

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

CodePudding user response:

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.

  • Related