EDIT: Amazingly, newacct's answer has accumulated 12 points in the four hours since I posted my question. This, despite its being incorrect. As alternatives to php's associative array, newacct offers Java's HashMap and Python's dictionary, neither of which preserves key order.
cmcg provided a correct answer for the Java version. That is, to use a LinkedHashMap to preserve key order. Milhous suggested a TreeMap, but Piligrim pointed out that a TreeMap sorts elements by key, while LinkedHashMap preserves original order, which was the intent.
Alexander Ljungberg first indicated that an ordered dictionary was not currently available for Python. Daniel Pryden then provided a simple and straightforward alternative structure, a list of two-tuples.
In the hope that my beginner's Python syntax is correct,
# a list of two-tuples
stateList = [('ALABAMA', 'AL'), ('ALASKA', 'AK'), ('WISCONSIN', 'WI'), ('WYOMING', 'WY')]
for name, abbreviation in stateList:
print name, abbreviation
Output:
ALABAMA AL
ALASKA AK
WISCONSIN WI
WYOMING WY
Which is exactly what was required.
Thanks to everyone who contributed. It's been educational.
In php one can handle a list of state names and their abbreviations with an associative array like this:
<?php
$stateArray = array (
"ALABAMA"=>"AL",
"ALASKA"=>"AK",
// etc...
"WYOMING"=>"WY");
foreach ($stateArray as $stateName => $stateAbbreviation)
{
print "The abbreviation for $stateName is $stateAbbreviation.\n\n";
}
?>
Output ( * with key order preserved * ):
The abbreviation for ALABAMA is AL.
The abbreviation for ALASKA is AK.
The abbreviation for WYOMING is WY.
EDIT: Note that the order of array elements is preserved in the output of the php version. The Java implementation, using a HashMap, does not guarantee the order of elements. Nor, in fact, does the dictionary in Python.
How is this done in java and python? I only find approaches that supply the value, given the key, like python's:
stateDict = {
"ALASKA" : "AK",
"WYOMING" : "WY"
}
for key in stateDict:
value = stateDict[key]
Many thanks.
Lasoldo Solsifa