How to access a dictionary value inside a list?

Question:

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!

Asked By: Sophie

||

Answers:

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.'
Answered By: Sash Sinha

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’]

Answered By: RBalloon

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).

Answered By: Said Amz

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']
Answered By: Joelinton
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.