Can anyone explain me this?


I'm not stuck or anything. Just don't understand why this works this way.

In particular this line is bugging me:

print key, my_dict[key]

wouldn't it have way more sense if it would work like this:

print key, value

my_dict = {
    "web": "JavaScript",
    "programming": "Ruby"
print my_dict.keys()
print my_dict.values()

for key in my_dict:
    print key, my_dict[key]


key and value are just terms that you use for a dictionary
in this case you've already separated the key using the for loop and stored it in a variable called key.
So its " print key, my_dict[key]
the my_dict[key] looks up the key reference and prints the value

I might be wrng though


Thanks anyway ! Appreciate it .....


@nekrodarkmoon, @markiscoding
What you learned::

  • when using the comma-separator in a print statement
    a space-character is used as a separator in the Diplay

  • a dictionary has 1 or more properties
    each property consists of a property-key and an associated Value
    to get access to the associated Value of a property
    you have 3 possibilities

    • using the so-called literal-key ( no variable allowed & the key has no-space's )
      my_dict.web ==output==> Javascript

    • using the so-called bracket-notation where you have 2 possibilities
      --1 using the literal-key as a string-Value within the brackets like
      my_disct["web"] ==output==> Javascript
      --2 using a variable within the brackets ( the variable having an associated string-Value )
      myVar = "web"
      my_dict[myVar] ==output==> Javascript

Now with FOR IN-loop you will iterate over a given dictionary
and at every iteration you will have captured the property-key in a variable of your choice
and then using the 2nd-option of the bracket notation to get at the associated Value.


Thanks for explaining to us both ....


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.