Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

break inner loops and pass control to outermost loop in python

Here is what I am looping through complex nested dictionaries inside a list called adm2_geonames. I then have a csv file whose line[1] needs to searched inside adm2_geonames. Once found, I want to break the loops for adm2_geonames i.e. starting from
for dic in adm2_geonames: and pass the control to for line in csvReader: for next keyword, until all in the csv are read.
I am confused about setting the scope for break statement. I have tried putting multiple break statements also for each inner loop. Seems, not the right approach.
Please I am a beginner python learner, so please be patient if my question is naĂŻve.

coords = []
with open('ADM2_hits.csv') as csvFile:
    csvReader = csv.reader(csvFile)
    next(csvReader)
    for line in csvReader:
        keyword = line[1]
        for dic in adm2_geonames:
            for key in dic:
                if(key == "geonames"):
                    for x in dic[key]:
                        if(keyword == x['name']):
                            line.append(x['lat'])
                            line.append(x['lng'])
                            coords.append(line)
                            break
print(coords)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

One approach is to use an else: block to capture the case in which the inner loop was not broken (in which case you want to continue), followed by a break to break the outer loop if the else hasn’t already continued it:

coords = []
with open('ADM2_hits.csv') as csvFile:
    csvReader = csv.reader(csvFile)
    next(csvReader)
    for line in csvReader:
        keyword = line[1]
        for dic in adm2_geonames:
            for x in dic["geonames"]:
                if(keyword == x['name']):
                    line.append(x['lat'])
                    line.append(x['lng'])
                    coords.append(line)
                    break
            else:
                continue
            break
print(coords)

Note that you can eliminate some of that inner looping by just going straight to dic["geonames"] instead of looping over the entire dictionary; the whole point of dictionaries is that you can jump straight to a given entry by its key instead of having to search the whole thing iteratively.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading