Home > database >  Reading dictionary in the list - python
Reading dictionary in the list - python

Time:11-24

I have a list like this (coming out of a json file reading):


list = [{'sheet_name': 'Daily', 'id_column': 'A', 'frequency': 'daily'}]

I want to read the value of the key 'id_column' but when I use:


list[0]['id_column']

it doesnt work

it considers each letter as a index in the list but not the dictionary. So this is what i get when trying to read indexes:


list[0] = [
list[1] = {

How can i read the key value in the dictionary in the list.

thanks

CodePudding user response:

Because the data you retried is in the form of 'String' or 'JsonArray of String'

You can use json.loads() python module to convert to actual Python List or Dictionary

import json

data = json.loads(list)  
print(data[0]['id_column'])

Please refer for more details, https://pythonexamples.org/python-json-to-list/

Note: I notice that you are defined the list name as 'list' it is highly recommended to avoid naming variables or functions which equals python builtins

  • Related