Write a dictionary to a csv file in tables. It keeps showing "String indices must be integers"

Question:

I want to write a table in csv file with a header [‘Username’, ‘INFO’, ‘ERROR’]

I have looked the "String indices must be integers" up online

Following the instructions, Python still keeps outputting the same type error

This is really upsetting

Does anyone know how to solve?

import csv

dict_data = {'ac': {'INFO': 2, 'ERROR': 2}, 'ahmed.miller': {'INFO': 2, 'ERROR': 4}, 'blossom': {'INFO': 2, 'ERROR': 6}, 'bpacheco': {'INFO': 0, 'ERROR': 2}, 'breee': {'INFO': 1, 'ERROR': 5}, 'britanni': {'INFO': 1, 'ERROR': 1}, 'enim.non': {'INFO': 2, 'ERROR': 3}, 'flavia': {'INFO': 0, 'ERROR': 5}, 'jackowens': {'INFO': 2, 'ERROR': 4}, 'kirknixon': {'INFO': 2, 'ERROR': 1}, 'mai.hendrix': {'INFO': 0, 'ERROR': 3}, 'mcintosh': {'INFO': 4, 'ERROR': 3}, 'mdouglas': {'INFO': 2, 'ERROR': 3}, 'montanap': {'INFO': 0, 'ERROR': 4}, 'noel': {'INFO': 6, 'ERROR': 3}, 'nonummy': {'INFO': 2, 'ERROR': 3}, 'oren': {'INFO': 2, 'ERROR': 7}, 'rr.robinson': {'INFO': 2, 'ERROR': 1}, 'sri': {'INFO': 2, 'ERROR': 2}, 'xlg': {'INFO': 0, 'ERROR': 4}}

with open("testinggg.csv", 'w') as output:
fields = ['Username', 'INFO', 'ERROR']
writer = csv.DictWriter(output, fieldnames=fields)
writer.writeheader()
for m in dict_data:
  print(m)
  writer.writerow({'Username': str(m[0]), 'INFO': str(m[1]['error']), 'ERROR': str(m[1]['info'])})

Python keeps showing this no matter how hard I try:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: string indices must be integers
Asked By: Kokonoeyuki

||

Answers:

for m in dict_data is only iterating the keys of the dict, which are strings. And you should see that with your print(m) statements:

ac
ahmed.miller
blossom
bpacheco
breee
...

The statement m[0] will give you just the first letter, like ‘a’ in ‘ac’. The statement m[1]['error'] is the source of your error; you’re treating the second letter, ‘c’ in ‘ac’, like it’s a dict.

To get your username, the key, and INFO/ERROR, the values, use the items() iterator:

for k, v in dict_data.items():
    writer.writerow({'Username': k, 'INFO': v['INFO'], 'ERROR': v['ERROR']})

You’ve also got errors in how you’re trying to access the sub-dicts:

  • the INFO/ERROR keys are capitalized
  • you swapped info/error in your example

The above code fixes both of those issues.

Answered By: Zach Young
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.