Fun with Dicts and Lists¶
Contents¶
Indices and tables¶
Iterating Over a List in Reverse¶
Sometimes it is useful to organize and manipulate data in lists and dictionaries. As usual there’s often more than one way to achieve our goals. In the following case we want to print a list in reverse.
The list object is a mutable sequence type and has a handy built-in function called reverse
. The order of the list elements is reversed in place, changing the original list.
After using reverse()
the list can be iterated over directly in a for
loop.
>>> foo = [1, 2, 3]
>>> foo
[1, 2, 3]
>>> foo.reverse()
>>> foo
[3, 2, 1]
>>> for i in foo :
... print (i)
...
3
2
1
Note
When making a copy of the list to prevent chaning the original data, remember that simply assigning a new name to the object is not enough. Use the list
constructor instead (SEE REFERNCE AT: TBD).
>>> bar = foo
>>> bar
[1, 2, 3]
>>> foo.reverse()
>>> foo
[3, 2, 1]
>>> bar
[3, 2, 1]
>>> baz = list(foo)
>>> baz
[1, 2, 3]
>>> foo.reverse()
>>> foo
[3, 2, 1]
>>> baz
[1, 2, 3]
- Another method would be to use the
reversed
function in the for loop >>> foo = [1, 2, 3] >>> for i in reversed(foo) : ... print (i) ... 3 2 1
- But wait, there’s more. Remember that handy ability to traverse a sequence backwards? And slices?
>>> foo = [1, 2, 3] >>> for i in foo[::-1] : ... print (i) 3 2 1
Note
The double colon :: represents the omission of the start and stop parameters, which default to 0 and -1. The third parameter is the step, the negative value indicating backwards traversal.
Sorting a Dictionary¶
A dictionary does not have the same ordering as a list. But what if we wished to sort the keys for some reason?
>>> dwarves = {'Balin':'East Gate, Moria',
'Oin':'West Gate, Moria',
'Thorin':'Near the Lonely Mountain',
'Fili':'Near the Lonely Mountain',
'Kili':'Near the Lonely Mountain',
'Gloin':'Unknown'}
>>> dwarves = {
... 'Balin':'East Gate, Moria',
... 'Oin':'West Gate, Moria',
... 'Thorin':'Near the Lonely Mountain',
... 'Fili':'Near the Lonely Mountain',
... 'Kili':'Near the Lonely Mountain',
... 'Gloin':'Unknown',
... 'Dwalin':'Erebor',
... 'Ori':'Balin\'s Tomb Moria',
... 'Dori':'Erebor',
... 'Nori':'Erebor',
... 'Bofur':'Unknown'}