8.7) Dictionaries: Indexing
Since dictionary elements are organised by keys rather than positions, you’ll have to use a key as an index.
Let’s consider the following dictionary:
>>> Bilbo={'Name':['Bilbo','Baggins'], 'Race':'Elf', 'Gender':'Male', 'DoB':[22,'September',2890]}
To get the gender of Bilbo, we do:
>>> Bilbo['Gender'] 'Male'
Indexing is always done with square brackets.
What will the following return? Try and work it out, and then check in IDLE.
>>> Bilbo['DoB'][2]
Was the answer, 2890?. Can you explain why?
Bilbo['DoB'] is a list with three elements so Bilbo['DoB'][2] will return the third element in the list, which corresponds to Bilbo’s year of birth.
You might have noticed a mistake in Bilbo’s race. Fortunately, dictionaries are mutable like lists, they can be modified. To correct our mistake:
>>> Bilbo['Race']='Hobbit' >>> print Bilbo['Race'] Hobbit