Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue in iterating over Python dictionaries with lists and sub-dictionaries

I have a data structure I have read from a file which looks like below –

data = {"test":['[{"Day":"Monday","Device":"Android","Data":[1, 2, 3]}, {"Day":"Tuesday","Device":"Iphone","Data":[10, 20, 30]}]']}

I am trying to access the elements of the structure like below, peeling off one by one –

value = data["test"]
print(value)
#['[{"Day":"Monday","Device":"Android","Data":[1, 2, 3]}, {"Day":"Tuesday","Device":"Iphone","Data":[10, 20, 30]}]']

value1 = value[0]
print(value1)
#[{"Day":"Monday","Device":"Android","Data":[1, 2, 3]}, {"Day":"Tuesday","Device":"Iphone","Data":[10, 20, 30]}]


print(value1[0]) 
#I get only [ as if it is a string

Does the incoming structure has some problems, or am I accessing the wrong way.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is the link to reproduce – https://godbolt.org/

>Solution :

You can use the built-in JSON parser to convert this to a dictionary like so:

import json

for item in json.loads(data['test'][0]):
    print(item, type(item))

# >>> {'Day': 'Monday', 'Device': 'Android', 'Data': [1, 2, 3]} <class 'dict'>
# >>> {'Day': 'Tuesday', 'Device': 'Iphone', 'Data': [10, 20, 30]} <class 'dict'>

Note: printing type(item) is just to demonstrate that they’re being converted to dict appropriately

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading