Iterating through a Dictionary

By | 25 July, 2012

Keeping things simple for anybody who does a search about this subject:

If we have a dictionary like this:

var dictio:Dictionary = new Dictionary();

dictio[“france”]=”paris”;

dictio[“england”]=”london”;

you can iterate like this:

Iterating through the keys:

for(var country:String in dictio){

trace(country); // this lists england, france

}

Iterating through the values:

for each(var capital:String in dictio){

trace(capital); // this lists london, paris

}

You can easily iterate through both keys and values, but its a hack since theres no native way to do it:

for(var country:String in dictio){

trace(country+” has the capital: “+dictio[country]);

}

The above code produces:

france has the capital: paris
england has the capital: london

Easy but also easily forgetable and confusing.

Resources:

Adobe livedocs about Dictionary