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)
CodePudding user response:
You don't need all these loops in the first
place, which means you don't need break
at all.
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:
try:
line.extend(dic['geonames']['name'][k] for k in ['lat', 'long'])
coords.append(line)
except KeyError:
continue
CodePudding user response:
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.