I am seeking some way to make this nested for loop more pythonic. Specifically, how can I iterate through unique combinations of three variables, and write to file if data is present in the dictionary?
foo,bar = {},{} #filling of dicts not shown
with open(someFile,'w') as aFile:
for year in years:
for state in states:
for county in counties:
try:foo[year,state,county],bar[state,county]
except:continue
aFile.write("content"+"\n")
You could just iterate over the keys of
fooand then check ifbarhas a corresponding key:This way you avoid iterating over anything that won’t at least work for
foo.The disadvantage to this is that you don’t know what order the keys will be iterated in. If you need them in sorted order you could do
for year, state, county in sorted(foo).As @Blckknght pointed out in a comment, this method also will always write for every matching key. If you want to exclude some years/states/counties you could add that to the
ifstatement (e.g.,if (state, county) in bar and year > 1990to exclude years before 1990, even if they are already in the dict).