# lists associate a number with each item in the list >>> l = [ 'a', 'b', 'c' ] >>> l[0] Out[3]: 'a' # dictionaries associate any immutable type with each item >>> d = { } >>> type(d) Out[5]: dict >>> d['a'] = 1 >>> d['b'] = 13 >>> d Out[8]: {'a': 1, 'b': 13} >>> d[(1, 2, 3)] = 'abc' >>> d Out[10]: {'a': 1, 'b': 13, (1, 2, 3): 'abc'} # lists are mutable, so cannot be used as a key >>> d[[1, 2, 3]] = 'def' Traceback (most recent call last): File "/Users/rcd/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2721, in run_code exec code_obj in self.user_global_ns, self.user_ns File "", line 1, in d[[1, 2, 3]] = 'def' TypeError: unhashable type: 'list' # the values associated with each key can be changed though >>> d['a'] += 1 >>> d Out[13]: {'a': 2, 'b': 13, (1, 2, 3): 'abc'} >>> d['def'] = [1, 2, 3] >>> d['def'] += [1] >>> d Out[16]: {'a': 2, 'b': 13, 'def': [1, 2, 3, 1], (1, 2, 3): 'abc'} # it is an error to try to access a key that does not exist in the dictionary >>> d['z'] += 1 Traceback (most recent call last): File "/Users/rcd/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2721, in run_code exec code_obj in self.user_global_ns, self.user_ns File "", line 1, in d['z'] += 1 KeyError: 'z' >>> d['z'] = 1 >>> d['z'] += 1 >>> d Out[20]: {'a': 2, 'b': 13, 'def': [1, 2, 3, 1], 'z': 2, (1, 2, 3): 'abc'} # there are a variety of ways to access the information in a dictionary >>> d.keys() Out[21]: ['a', 'b', 'z', 'def', (1, 2, 3)] >>> d.values() Out[22]: [2, 13, 2, [1, 2, 3, 1], 'abc'] >>> m = max(d.keys()) >>> m Out[25]: (1, 2, 3) # note, the lists returned by keys and values are parallel structures >>> d.keys().index(m) Out[26]: 4 >>> d.values()[4] Out[28]: 'abc' # items is the shorthand for getting both keys and values together >>> d.items() Out[29]: [('a', 2), ('b', 13), ('z', 2), ('def', [1, 2, 3, 1]), ((1, 2, 3), 'abc')] # another way to do the same thing >>> zip(d.keys(), d.values()) Out[30]: [('a', 2), ('b', 13), ('z', 2), ('def', [1, 2, 3, 1]), ((1, 2, 3), 'abc')] # looping over the items in a dictionary: two ways >>> for item in d.items(): ... print(str(item[0]) + '\t' + str(item[1])) ... a 2 b 13 z 2 def [1, 2, 3, 1] (1, 2, 3) abc >>> for (k,v) in d.items(): ... print(str(k) + '\t' + str(v)) ... a 2 b 13 z 2 def [1, 2, 3, 1] (1, 2, 3) abc