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"]
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object.
String Indexing In Python, strings are ordered sequences of character data, and thus can be indexed in this way. Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ).
Indexing using index arraysIndexing can be done in numpy by using an array as an index. In case of slice, a view or shallow copy of the array is returned but in index array a copy of the original array is returned. Numpy arrays can be indexed with other arrays or any other sequence with the exception of tuples.
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"]
In Python 3, you'll get a dict_keys
, which is a view and a bit more efficient (see views docs and PEP 3106 for details).
print(myDict.keys()) # => dict_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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With