3

I am trying to read a list within a list and add keys and values to a dictionary within a dictionary. But I get the 'str' object doesn't support assignment error.

Code:

report_dict = dict()
axis_list = []
results = self.report_data(conn)
for row in results:
  try:
    report_dict[row[0]] = row[3]
    report_dict[row[0]][row[3]] = row[1]
  except IndexError:
    None 
  print(report_dict)

Result:

report_dict = { abc: {qwe:asd}, …..}
4
  • 1
    Can you post a sample of what results looks like? Commented Feb 13, 2020 at 14:55
  • @Wondercricket done. Commented Feb 13, 2020 at 14:56
  • @qwerty I think @Wondercricket meant the results variable in your code, not the desired result of your code. Commented Feb 13, 2020 at 15:00
  • Its just a list within a list. So essentially row is a list from which I am inputting abc, qwe,asd into the dictionary Commented Feb 13, 2020 at 15:02

1 Answer 1

2

I think what you're trying to do is make a nested dictionary. If I understand your input correctly, your code could be fixed just by setting report_dict[row[0]] to an empty dict, by changing

report_dict[row[0]] = row[3]

to

report_dict[row[0]] = {}

This would make the next line,

report_dict[row[0]][row[3]] = row[1]

add the key row[3] with value row[1] to the dictionary report_dict[row[0]]. This would give us:

report_dict = {row[0]: {row[3]: row[1]}, ...}

which I think is your expected output.

Sign up to request clarification or add additional context in comments.

5 Comments

report_dict[row[0]] = {} in the for loop, wont it cause the data to be overwritten if the first key is same? Check the expected result.
@qwerty yes, you can't have duplicate keys in a dictionary. Please ask your new requirements in a new question rather than editing this answered question!
Okay, what would you do for duplicated keys, append it to another dictionary?
@qwerty depends what you want your data structure to be?
end of the day it should be a dictionary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.