Is it possible to use strings as indices in an array in python?
For example:
myArray = []
myArray["john"] = "johns value"
myArray["jeff"] = "jeffs value"
print myArray["john"]
解决方案
What you want is called an associative array. In python these are called dictionaries.
Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.
myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"
Alternative way to create the above dict:
myDict = {"john": "johns value", "jeff": "jeffs value"}
Accessing values:
print myDict["jeff"] # => "jeffs value"
Getting the keys (in Python v2):
print myDict.keys() # => ["john", "jeff"]
If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".