Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Array with String Indices

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"] 
like image 799
Petey B Avatar asked Sep 22 '10 00:09

Petey B


People also ask

Can you index an array with string?

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.

Can you index strings in Python?

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 ( [] ).

Can you index an array Python?

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.


1 Answers

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".

like image 163
miku Avatar answered Oct 13 '22 13:10

miku