Mark
Mark

Reputation: 79

Python 3 - Array in Array

I just started learning python3 about a week and a half ago. Now the books covers lists, tuples and directory. I hope my question is not to dumb but I couldn't find the answer anywhere.

Say, I have a list of names with the ages of the people:

Klaus, 34
Doris, 20
Mark, 44
Tina, 19

What I would like to have (and what I could do in php :-) ) is a multidimensional array like

1st array(name=Klaus, age=34), 
2nd array(name=Doris, age=20), 
3rd array(name=Mark, age=44), 
4th array(name=Tina, age=19)

in php it would look like:

$multiarray = array(array(name =>"Peter", age=>34),
                    array(name=>"Doris",age=>20),
                    array(name=>"Mark",age=>44),
                    array(name=>"Tina", age=>19));

how do I do this in python3?

Again sorry for a probably dumb question :-)

Mark

Upvotes: 0

Views: 1399

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 121987

In Python, this would probably be a list of dictionaries:

multiarray = [{"name": "Peter", "age": 34}, ...]

e.g. Peter's age would be

multiarray[0]["age"]

Having just spotted your comment, note that you can do

for person in multiarray:
    print("{0[name]} is {0[age]} years old.".format(person))

Manually incrementing an index i is not very Pythonic: you can either:

  1. Iterate through the items directly (for item in lst);
  2. Use enumerate to get the item and index (for index, item in enumerate(lst)); or
  3. Use range to generate the indices (for index in range(len(lst))).

Upvotes: 1

Related Questions