0

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

2
  • Why not use just one dictionary? {'Peter': 34, 'Doris': 20, ...} Commented Feb 17, 2014 at 9:34
  • I would like to do something like this: length = len(multiarray) i = 0 while i < length: print("{name} is {age} years old".format(multiarray[i]["name"], multiarray[i]["age"])) i += 1 Commented Feb 17, 2014 at 9:43

1 Answer 1

1

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))).
Sign up to request clarification or add additional context in comments.

7 Comments

Ahh, this makes sense. Lists, Tuples and Dictionaries confuse me a little bit - Hope this will get better :-)
I have updated my answer to reflect your comment on the question
you're a goldmine :) Thanks for helping me out. Seems I have to get another book which goes into more details about all the list, tupels and dictionary stuff
I found another soulution: persons = {"Dieter":34, "Doris":20, "Petra":29, "Mark":24} print(persons) for name, age in persons.items(): print("{0} ist {1} Jahre alt".format(name, age)) This works perfect for me :-)
Yes, that will work fine if you only have one parameter per person. You could also use a dictionary of dictionaries: {'Mark':{'age': 24}, ...}` allowing you to have multiple parameters (e.g. 'occupation', 'address', ...) per person, or even create a custom Person class allowing the addition of specific functions to a person.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.