Osama Yawar
Osama Yawar

Reputation: 369

Passing values to array indexes in Python

Is there any way to assign values to keys in array in Python?

Example in PHP:

$inputArr = array(
                'vertex'=>values[0],
                'visited'=>values[1],
                'letter' => $values[2]
                )

This is the way i tried to do in Python:

file_name = input('Enter a file name: ')
f = open(file_name, 'r')
data = f.readlines() //Read the lines
for line in data: 
      values = line.split(' ') Split line following the spaces
      inputArr = array(
                'vertex'=>values[0], //Pass each value to a key in that array
                'visited'=>values[1],
                'letter' => $values[2]
                )
      print (inputArr)

Upvotes: 0

Views: 74

Answers (2)

Bakuriu
Bakuriu

Reputation: 101959

You want to use dicts:

array = {
    'vertex': values[0],
    'visited': values[1],
    'letter': values[2],
}
# access via array['vertex']

Note however that this does not preserve the order. Iterating over the dictionary can produce an arbitrary order. There is an OrderedDict class in recent versions of python, however keep in mind that it takes more than twice as much memory as a plain dict.

If your array is fixed, and only has those 3 elements, it might be better to use a namedtuple:

from collections import namedtuple

NamedSeq = namedtuple('NamedSeq', ('vertex', 'visited', 'letter'))

array = NamedSeq(values[0], values[1], values[2])
#or
array = NamedSeq(vertex=values[0], letter=values[2], visited=values[1])

This preserves the order and you can access vertex via array.vertex etc. Or you can access the data using array[0] for the value of vertex, array[1] for the visited etc.

Note that however that namedtuples are immutable, i.e. you cannot modify them.

Upvotes: 6

Guy Gavriely
Guy Gavriely

Reputation: 11396

@Bakuriu's answer is correct

you can also do something like this:

for line in data: 
    vertex, visited, letter = line.split() # space is default
    print vertex, visited, letter

Upvotes: 1

Related Questions