Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

How can I simplify and optimize this code?

if type(variant_list) == dict:
    style_color_if(variant_list[style_colors_main], variant_list)
else:
    for variant in variant_list:
        if type(variant[style_colors_main]) == dict:
            json_key_getter(variant[style_colors_main], variant)
        else:
            for styleColors in variant[style_colors_main]:
                if type(styleColors) == dict:
                    json_key_getter(styleColors, variant)
                else:
                    for styleColor in styleColors:
                        json_key_getter(styleColor, variant)

Example of one element of variant list, variant list can have one such thing or many:

http://pastebin.com/axuvzZnh

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

Recursion here is going to be your friend:

def recurse_json(property, variant):
    # This is our exit condition
    if isinstance(property, dict):
        json_key_getter(property, variant)
    else:
        # Otherwise, WE NEED TO GO DEEPER!
        for item in property:
            recurse_json(item, variant)

Now all you have to do is call this function in your for loop:

# Use `isinstance` to check for types as it takes inheritance into account.
if isinstance(variant_list, dict):
    style_color_if(variant_list[style_colors_main], variant_list)
else:
    for variant in variant_list:
        try:
            recurse_json(variant[style_colors_main], variant)
        except KeyError:
            print('Property had no "{}" property'.format(style_color_main))

I had to put in the try-except blocks because in your example the first element of the list did not have the productStyleColors property (which is what I assume is in style_color_main).

The use of isinstance isn't ideal because we would typically like to use try-excepts blocks. However, because I don't know if your other functions throw any exceptions, I chose to use (as the link says) the 'less-bad option'.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.