views:

96

answers:

2

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"]
+14  A: 

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: http://us.pycon.org/2010/conference/schedule/event/12/. It's called the "The Mighty Dictionary".

The MYYN
Great example. Something always good to know about Dictionaries in Python is that, as [The MYYN](http://stackoverflow.com/users/89391/the-myyn) said, the key must be of an immutable type. If you ever need to categorise values with "multiple" keys, you have to use the Tuple type in Python.
Sean
Technically the key [has to be _hashable_ ](http://docs.python.org/reference/datamodel.html#object.__hash__), not necessarily immutable, although the value returned by the `hash` function should not change as long as the object is used as a dictionary key. If it does, be prepared for your program to crash or misbehave in bizarre ways.
David Zaslavsky
+1  A: 

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

Jeff
Note that needing an OrderedDict is much less common than needing a dict.
Mike Graham