0

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)
1
  • You have an error on your 'letter' line -> 'letter' => $values[2].. also, arrays in python are dicts. so try using a dictionary Commented Jan 20, 2014 at 21:37

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

@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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.