Ask Your Question
1

multidictionaries

asked 2010-12-15 09:59:52 +0100

Hello!

I need to store more data, and in order to do so, I would need multi-dimensional version of a dictionary... For example, let m be an object such that if you give the name and the age, such as m [Cathy, 19], then it returns the phone number. (In a dictionary you have one variable, and now I must call the data by more variables...) Do you know such a command?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
4

answered 2010-12-15 10:16:19 +0100

Jason Bandlow gravatar image

If I correctly understand your question, dictionaries can do this. You just need to use tuples as keys. Example:

sage: m = {} # an empty dictionary
sage: m[('Cathy', 19)] = '555-1212'
sage: m[('Cathy', 19)]
'555-1212'
edit flag offensive delete link more

Comments

Thank you very much! (I also thought a similar thing but with lists in the argument. But I prefer tuples :-) )

Katika gravatar imageKatika ( 2010-12-15 11:05:50 +0100 )edit

You're welcome! In fact, lists won't work as keys. Look up 'mutable' vs. 'immutable' in connection with Python to understand why.

Jason Bandlow gravatar imageJason Bandlow ( 2010-12-15 13:43:38 +0100 )edit

You can also construct the tuples "implicitly" by doing m['Cathy', 19] = '555-1212' .

Mike Hansen gravatar imageMike Hansen ( 2010-12-15 14:45:48 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2010-12-15 09:59:52 +0100

Seen: 382 times

Last updated: Dec 15 '10