I am trying to store a dictionary item but i receive this particular error and i can't seem to wrap my head around why my dictionnary looks like this
comment = {'en': 'The SIDHistory attribute must be cleared', 'fr': "L'attribut SIDHistory doit être effacé"}
and the function I use is
if y.get('comment'):
# print('Comment :')
comments = y.get('comment')
print(comments)
print(comments["en"])
print(comments["fr"])
# print(' Comment in English :', comment['en'])
field_comment_english = comments["en"]
# print(' Comment in French :', comment['fr'])
field_comment_french = comments["fr"]
else:
# print(' Comment in English : None')
# print(' Comment in French : None')
field_comment_english = 'None'
field_comment_french = 'None'
It prints the variable I want without problem but then I receive an error at the end of the compilation telling me
File "/Users/cmahouve/PycharmProjects/secad/apps/rules_management/views.py", line 50, in all_rules_interpreter
print(comments["en"])
TypeError: string indices must be integers
CodePudding user response:
This is not a dictionary, but a string with as content that looks like something that is a dictionary. You can use the .literal_eval(…)
function [Python-doc] of the ast
module to parse this into a dictionary:
from ast import literal_eval
if y.get('comment'):
comments = literal_eval(y.get('comment'))
# …
But the question is why this is a string, there might be a problem more upstream where the y
is "populated" with data.