I am trying to load a JSON file with Python and extract only the necessary data with the following code. Is there any way to accomplish this in a better/simpler way? I feel like this could be done using defaultdict in collections and without if statement but cannot figure out.
import json
with open('somedata.json') as f:
json_data = json.load(f)
main_dict = {}
for item in json_data:
values1_list = item['sub_values1']
values2_str = item['sub_values2']
if item['main_key'] in main_dict:
main_dict[item['main_key']]['sub_key1'].append(values1_list)
else:
main_dict['main_key'] = {'sub_key1': values1_list, 'sub_key2': values2_str}