Simplifying the code with same list comprehensions I have such method where:


primary_images is dict,  
additional is dict, 
get_uri_text is some decorating method, 
marker is telling how to parse two dicts.


How can I simplify this method?

    @staticmethod
    def decorate_sort_images(primary_images, additional_images, get_uri_text, marker=False):
        srt_keys = sorted(primary_images.keys())
        new_result = OrderedDict()
        if not additional_images:
            #only primary
            for _key in srt_keys:
                new_result[_key] = [get_uri_text(iter_el) for iter_el in primary_images[_key]]
            return new_result
        for _key in srt_keys:
            new_result[_key] = [get_uri_text(iter_el) for iter_el in primary_images[_key]]
            if marker:
                if _key in additional_images:
                    new_result[_key] += [get_uri_text(iter_el) for iter_el in additional_images[_key]]
            else:
                new_result[_key] += [get_uri_text(iter_el) for iter_el in additional_images[_key]]
        return new_result
As far as I can tell, the difference between the conditional branches is only whether or not to avoid KeyError occurring at additional_images[_key] when key does not exist. This code should have the same behavior:

@staticmethod
def decorate_sort_images(primary_images, additional_images, get_uri_text, marker=False):
    srt_keys = sorted(primary_images)
    new_result = OrderedDict()
    allow_key_error = additional_images and not marker
    for _key in srt_keys:
        new_result[_key] = [get_uri_text(iter_el) for iter_el in primary_images[_key]]
        if allow_key_error or _key in additional_images:
            new_result[_key] += [get_uri_text(iter_el) for iter_el in additional_images[_key]]
    return new_result        


When additional_images is empty, _key in additional_images is always False, so we don't need the first if statement any more. 

Note that I also removed a redundant .keys() from sorted(primary_images).