1

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}

1 Answer 1

1

You can use the setdefault method on your main_dict:

main_dict = {}
for item in json_data:
    values1_list = item['sub_values1']
    values2_str = item['sub_values2']
    vals = main_dict.setdefault('main_key', {'sub_key1': values1_list, 'sub_key2': values2_str})
    vals['sub_key1'].append(values1_list)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.