Manish Yadav
Manish Yadav

Reputation: 3

how to remove double for loops in the code?

how can i reduce complexity created by for loops. is there any alternative for double for loops ?

Final_list = [{"Owner" : "b", "c" : "d", "e" : "f"}, {"Owner" : "x", "c" : "d", "e" : "f"}]
Image_Owners = ["x", "y", "z"]
def imagesbyowner():
    for owner in Image_Owners:
        for element in Final_list:
            if element["Owner"] == owner:
                print(json.dumps(element,indent=0, separators=('', ':')))
                #print(yaml.dump(element, allow_unicode=False, default_flow_style=False))
imagesbyowner()

Upvotes: 0

Views: 94

Answers (2)

SamR
SamR

Reputation: 20435

I would pass the owner as a parameter to imagesbyowner, taking it out of the loop inside the function. I would also make both loops list comprehensions:

def imagesbyowner(owner, Final_list = Final_list):
    items = [item for item in Final_list if item['Owner']==owner]
    items = items if items != [] else {owner : "none"}
    return json.dumps(items)

[imagesbyowner(owner) for owner in Image_Owners]

# Output:
# ['[{"Owner": "x", "c": "d", "e": "f"}]', '{"y": "none"}', '{"z": "none"}']

Edit: added line to deal with empty list

Upvotes: 0

Ukulele
Ukulele

Reputation: 695

The double for loops are fine, but if you really want to get rid of them you can loop over Final_list first (this isn't necessarily better though):

Final_list = [{"Owner" : "b", "c" : "d", "e" : "f"}, {"Owner" : "x", "c" : "d", "e" : "f"}]
Image_Owners = ["x", "y", "z"]
def imagesbyowner():
    for element in Final_list:
        if element["Owner"] in Image_Owners:
                # You can get owner now with Image_Owners.index(element["Owner"])
                print(json.dumps(element,indent=0, separators=('', ':')))
                #print(yaml.dump(element, allow_unicode=False, default_flow_style=False))
imagesbyowner()

Upvotes: 3

Related Questions