I would like to access the value of the following :
a = [{'translation_text': 'I love cake.'}]
Desired output:
"I love cake."
I tried the following:
a['translation_text']
and I get the following error:
TypeError: string indices must be integers
Has anyone experienced the same issue before? Thanks a lot for your help!
CodePudding user response:
The dictionary is the first item of the list a
, i.e., you need to access it by using its index, 0
:
>>> a = [{'translation_text': 'I love cake.'}]
>>> a[0]
{'translation_text': 'I love cake.'}
>>> a[0]['translation_text']
'I love cake.'
CodePudding user response:
just like that :
a[0]['translation_text']
a is a list. So before accessing to the key 'translation_text', you have to acess to the first element of the list (your dictionary).
CodePudding user response:
Your variable "a" is a list, containing one element that is a dictionary. You have to access first the dictionary a[0] and then add the key 'translation_text', so what you need is a[0]['translation_text']
CodePudding user response:
Dictionary mostly is using key,value pairs for example 'translation_text' is key and value is 'I love cake.' And with get() we can get the value from the key in a dictionary
a = {'translation_text': 'I love cake.'}
print(a.get('translation_text'))
Second Solution:
a[0]['translation_text']