I want to extract all key-value pairs from JSON file, I loaded it as a Python dictionary. I created this function below that stores all values. However, I am struggling to put them inside a list to store them like that. Any support is very appreciated.
json_example = {'name': 'TheDude',
'age': '19',
'hobbies': {
'love': 'eating',
'hate': 'reading',
'like': [
{'outdoor': {
'teamsport': 'soccer',
}
}
]
}
}
# My code - Extract values
def extract_values(dct, lst=[]):
if not isinstance(dct, (list, dict)):
lst.append(dct)
elif isinstance(dct, list):
for i in dct:
extract_values(i, lst)
elif isinstance(dct, dict):
for v in dct.values():
extract_values(v, lst)
return lst
# Extract keys
def matt_keys(dct):
if not isinstance(dct, (list, dict)):
return ['']
if isinstance(dct, list):
return [dk for i in dct for dk in matt_keys(i)]
return [k+('_'+dk if dk else '') for k, v in dct.items() for dk in matt_keys(v)]
Current output:
['TheDude', '19', 'eating'...]
Desired output:
[('name': 'TheDude'), ('age', '19'), ..., ('hobbies_love', 'eating'), ... , ('hobbies_like_outdoor_teamsport', 'soccer')]
Also if there is a more efficient or cleaner way to extract this, then it would be great.