This Is Key (and I don't understand)


#1


https://www.codecademy.com/en/courses/python-beginner-en-IZ9Ra/0/2?curriculum_id=4f89dab3d788890003000096

Add your code below!

for random in webster:
print webster[random]

I don't understand how this prints out the keys. I'm essentially typing in a random word... in the dictionary webster, and then asking it to print the key 'random' which then someone is valid and prints all of the keys.

I do not understand what is happening.. whatsoever, I attempted to grasph the concept from a couple of other post, some how i'm just not comprehending whats going on for this to work.

webster = {
	"Aardvark" : "A star of a popular children's cartoon show.",
    "Baa" : "The sound a goat makes.",
    "Carpet": "Goes on the floor.",
    "Dab": "A small amount."
}

# Add your code below!
for random in webster:
    print webster[random]


#2

This is a module name in Python and not a suitable name for a variable. key is adequate.

    for key in webster:
        print key

will print the keys, only.

    for key in webster:
        print webster[key]

will print the values, only

    for key in webster:
        print "%s: %s" % (key, webster[key])

will print the key - value pairs.


#3

Okay, so is 'key' a variable we are just creating for the time being or is it an actual variable already defined and understood in python?

Also for : print "%s: %s" % (key, webster[key])

What is the % doing?


#4

Yes, exactly. It is scoped to the block only, and is discarded when the for loop is complete.

As a general rule, the name we use should not exist in an outer scope.

Lastly, key names are always string type. Values can be any object.


#5

The % operator for strings reads the format specifiers in the string and replaces them according to specification (%s is just default conversion to string which will often be all you want)


#6

This makes much more sense... So in a for loop..

We are just creating a variable that holds the value of the definition's keys? Does that sound about right?

The % operator for strings reads the format specifiers in the string and replaces them according to specification (%s is just default conversion to string which will often be all you want)

I understand that %s stands for string ( the next one defined) however just the % alone before the defined %strings in parantheses.. still not grasping it.


#7

class ModuloExample(str):
    def __mod__(self, other):
        print 'left operand:', self
        print 'right operand:', str(other)

ModuloExample('blahblah') % 73

% is an operator just like +-*/ and operators do whatever the left value type defines it to do. For string, it replaces format specifiers, in my example above, it rather uselessly prints out the left and right operand.