[Tutor] Truckers Log....Me Again
Paul Sidorsky
paulsid@shaw.ca
Tue, 22 Jan 2002 11:11:46 -0700
Erik Price wrote:
> > {"key1": 12, "key2": "hi", key3: [2, 4, 6], key4: (1, 2, 3)}
>
> Here you've set up a dictionary.
Right. (Except I left the quotes off of "key3" and "key4" - Oops.)
> > [["key1", 12], ["key2", "hi"], ["key3", [2, 4, 6]], ["key4", (1, 2, 3)]]
>
> At this point, is it still a dictionary? Or have you performed some
> operation to make it a list? I see the square brackets, which if I
> recall correctly, surround lists.
Yes, this is entirely a list of lists. There is no dictionary involved,
but functionally these lists are similar. Accessing it is a real pain,
though. (I can give an example if needed.)
> > keys = ["key1", "key2", "key3", "key4"]
> > values = [12, "hi", [2, 4, 6], (1, 2, 3)]
>
> Two separate lists.
Right. As you might have seen already, dictionaries can actually be
told to produce these lists, using mydict.keys() and mydict.values().
Accessing this is a bit easier, again I could provide an example if it
would help
> > The concept of subscripting with, say, a string (e.g. mydict["key1"])
> > may seem unusual at first, but it does become natural! Subscripting
> > with a more complex object like a tuple or a class is even more bizzare
> > the first time you do it but it does save tons of work!
>
> I'm not sure that I follow you correctly -- I see what you're saying in
> the last paragraph but I haven't put together how it applies to the
> examples above.
mydict["key1"] would return just the number 12 in my example. Of course
I was referring to how conceptionally unusual this is for people used to
using only numbers inside the brackets.
I didn't use any fancier indexing there, but if you want to you can do
something like this:
>>> d = {("Paul", "Sidorsky"): "paulsid@shaw.ca"}
>>> print d[("Paul", "Sidorsky")]
paulsid@shaw.ca
This particular example isn't very practical, but when you need to
attach some information to multiple identifying values it can be quite
useful to set it up as a dictionary indexed using a tuple or other
object.
> Especially confusing (to me) is how Python allows you to define a
> dictionary, but then split that up into a variable "keys" and a variable
> "values", as shown above. But then, it's possible that the reference I
> used hasn't gotten that far yet.
Up to Python 2.1 this is often used for traversing an entire dictionary,
say to print the data in it:
for key in dict.keys():
print dict[key]
Of course in 2.2 you can now do this instead:
for key in dict:
print dict[key]
Unfortunately, I can't really think of a good way to view dictionaries
conceptually, so I'll have to leave that to somebody else!
--
======================================================================
Paul Sidorsky Calgary, Canada
paulsid@shaw.ca http://members.shaw.ca/paulsid/