Using Strings to Name Hash Keys?
I'm working through a book called "Head First Programming," and there's a
particular part where I'm confused as to why they're doing this.
There doesn't appear to be any reasoning for it, nor any explanation
anywhere in the text.
The issue in question is in using multiple-assignment to assign split data
from a string into a hash (which doesn't make sense as to why they're
using a hash, if you ask me, but that's a separate issue). Here's the
example code:
line = "101;Johnny 'wave-boy' Jones;USA;8.32;Fish;21"
s = {}
(s['id'], s['name'], s['country'], s['average'], s['board'], s['age']) =
line.split(";")
I understand that this will take the string line and split it up into each
named part, but I don't understand why what I think are keys are being
named by using a string, when just a few pages prior, they were named like
any other variable, without single quotes.
The purpose of the individual parts is to be searched based on an
individual element and then printed on screen. For example, being able to
search by ID number and then return the entire thing.
The language in question is Python, if that makes any difference. This is
rather confusing for me, since I'm trying to learn this stuff on my own.
My personal best guess is that it doesn't make any difference and that it
was personal preference on part of the authors, but it bewilders me that
they would suddenly change form like that without it having any meaning,
and further bothers me that they don't explain it.
EDIT: So I tried printing the id key both with and without single quotes
around the name, and it worked perfectly fine, either way. Therefore, I'd
have to assume it's a matter of personal preference, but I still would
like some info from someone who actually knows what they're doing as to
whether it actually makes a difference, in the long run.
EDIT 2: Apparently, it doesn't make any sense as to how my Python
interpreter is actually working with what I've given it, so I made a
screen capture of it working https://www.youtube.com/watch?v=52GQJEeSwUA
No comments:
Post a Comment