This Next Part is Key - { } [ ] ( )


#1

Assigning a dictionary with three key-value pairs to residents:

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

print residents['Puffin'] # Prints Puffin's room number

print residents['Sloth']
print residents['Burmese Python']

Ok, I undertand how to make this work. And I'm beginning to learn about dictionaries and keys and { }. But then [ ] comes back. So in this example we have { } and [ ].

This is were I feel like I'm going to get lost. There are { } after residents =. How come print residents['Puffin'] have [ ] symbols and not { } or ( )?


#2

Lets set a couple of things apart: when defining a variable you use:

[ ] for a list. I.e.

my_list = [1,2,3]

{ } for a dictionary. I.e

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

( ) for a tuple, I.e.

(1, 2)

When accessing the values of a list or dictionary, you use the square bracket notation.

residents['Puffin'] # value: 104

Just like a list:

my_list[1] # value: 2

If you were to use normal brackets ( ) it would indicate a function call, which is something completely different.
As for residents{'puffin'}, the Python interpreter would not allow this as the syntax is invalid.


#3

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