## COMPARISON OF 2 WAYS TO LOOP TO ASSIGN VALUES BASED ON CONDITIONS ## Imagine we have are looping through rows in an attribute table, or a similar task. ## In this example, since we don't have an attribute table, imagine that we already have field ## values stored in a list. ## INEFFICIENT WAY towns = ['Banff', 'Canmore', 'Calgary', 'Chestermere', 'Airdrie', 'Edmonton', 'Montreal', 'Madrid', 'Barcelona', 'London', 'Rabat'] for town in towns: if town in ('Madrid', 'Barcelona'): print 'Hey, %s is in Spain!' % town elif town == 'London': print 'Hey, %s is in UK!' % town elif town == 'Rabat': print 'Hey, %s is in Morocco!' % town else: print 'Hey, %s is in Canada!' % town print '\n-------------------------------------------------------------------------------\n' ## EFFICIENT WAY ctrs_cds = {'cn':'Canada', 'sp':'Spain','uk':'UK','mr':'Morocco'} dict_towns_countries = {'Banff': ctrs_cds['cn'], 'Canmore': ctrs_cds['cn'], 'Calgary': ctrs_cds['cn'], 'Chestermere': ctrs_cds['cn'], 'Airdrie': ctrs_cds['cn'], 'Edmonton': ctrs_cds['cn'], 'Montreal': ctrs_cds['cn'], 'Madrid':ctrs_cds['sp'], 'Barcelona':ctrs_cds['sp'], 'London':ctrs_cds['uk'], 'Rabat':ctrs_cds['mr']} for key in dict_towns_countries: print 'Oh, yes, %s is in %s' % (key, dict_towns_countries[key])
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question