Is there a way to extract data from the value of a key from list of dictionary in the list form using python

I’m trying to extract data from following HTML code:

"profile"[{"emp_id":"ABC0001","emp_info":{"age":"35yrs","gender":"Male","dob":"24jan1988","address":"xyz"},"emgy_contact":"abcd_1223456"}]

using the following codes:

for item in data['profile']:
    for key, val in item.items():
        print(f'{key}: {val}')

got this result:

emp_id: ABC0001
emp_info: {"age":"35yrs","gender":"Male","dob":"24jan1988","address":"xyz"},"emgy_contact":"abcd_1223456"}

What i’m looing for is this result:

emp_id: ABC0001
emp_info: 
age: 35yrs
gender: Male
dob: 24jan1988
address: xyz
emgy_contact:abcd_1223456

can anyone here help me out, Thank you

>Solution :

Add another nested loop when the value is a nested dictionary.

for item in data['profile']:
    for key, value in item.items():
        if isinstance(value, dict):
            for key1, value1 in value.items():
                print(f'{key1}: {value1}')
        else:
            print(f'{key}: {value}')
    print()

Leave a Reply