9.11.5. Dictionaries, Lists and Tuples#
9.11.5.1. Dictionaries#
One of Python’s built-in datatypes is the dictionary, which defines one-to-one relationships between keys and values.
9.11.5.1.1. Defining Dictionaries#
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}
. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.
1d = {"lens":"zoom", "software":"itom"}
2print(d)
3
4# 'lens' is a key and its associated value is 'zoom'. It can be referenced by d["lens"].
5print(d["lens"])
6
7# 'software' is a key and its associated value is 'itom'. It can be referenced by d["software"].
8print(d["software"])
9
10# You can get values by key, but you can't get keys by value.
11# So d["lens"] is 'zoom', but d["zoom"] raises an exception, because 'zoom' is not a key.
12print(d["zoom"])
{'lens': 'zoom', 'software': 'itom'}
zoom
itom
Traceback (most recent call last):
File "..", line ?, in <module>
KeyError: 'zoom'
9.11.5.1.2. Modifying Dictionaries#
You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value. You can add new key-value pairs at any time. This syntax is identical to modifying existing values. Dictionaries have no concept of order among elements.
1d = {"lens":"zoom", "software":"itom"}
2print(d)
3
4d["software"] = "itom"
5print(d)
6
7d["institute"] = "ITO"
8print(d)
9
10# Dictionary keys can be modified. The old value is simply replaced with a new one.
11d["institute"] = "none"
12print(d)
13
14# Dictionary keys are case-sensitive. Here, a new key-value pair will be created.
15d["Institute"] = "another"
16print(d)
{'software': 'itom', 'lens': 'zoom'}
{'software': 'itom', 'lens': 'zoom'}
{'software': 'itom', 'institute': 'ITO', 'lens': 'zoom'}
{'software': 'itom', 'institute': 'none', 'lens': 'zoom'}
{'Institute': 'another', 'software': 'itom', 'institute': 'none', 'lens': 'zoom'}
Dictionaries aren’t just for strings. Dictionary values can be any datatype, including strings, integers, objects, or even other dictionaries. Within a single dictionary, the values don’t all need to be the same type; you can mix and match as needed. Dictionary keys are more restricted, but they can be strings, integers, and a few other types. You can also mix and match key datatypes within a dictionary.
1d = {'lens': 'zoom', 'institute': 'ITO', 'software': 'itom'}
2print(d)
3
4d["version"] = 3
5print(d)
6
7d[42] = "douglas"
8print(d)
{'lens': 'zoom', 'institute': 'ITO', 'software': 'itom', 'version': 3}
{'lens': 'zoom', 'institute': 'ITO', 'software': 'itom', 42: 'douglas', 'version': 3}
9.11.5.1.3. Deleting Items From Dictionaries#
1d = {'lens': 'zoom', 'institute': 'ITO', 'software': 'itom', 42: 'douglas', 'retrycount': 3}
2print(d)
3
4# delete individual items from a dictionary by key
5del d[42]
6print(d)
7
8# delete all items from a dictionary
9# Note that the set of empty curly braces in the output signifies a dictionary without any items.
10d.clear()
11print(d)
{'lens': 'zoom', 'institute': 'ITO', 'software': 'itom', 42: 'douglas', 'retrycount': 3}
{'lens': 'zoom', 'institute': 'ITO', 'software': 'itom', 'retrycount': 3}
{}
9.11.5.2. Lists#
Lists are Python’s workhorse datatype. Variables can be named anything, and Python keeps track of the datatype internally.
9.11.5.2.1. Defining Lists#
A list is an ordered set of elements enclosed in square brackets. It can be used like a zero-based array.
1# A list of five elements is defined. Note that they retain their original order.
2li = ["a", "b", "zoom", "z", "example"]
3print(li)
4
5# The first element of any non-empty list is always li[0]
6print(li[0])
7
8# The last element of this five-element list is li[4].
9print(li[4])
['a', 'b', 'zoom', 'z', 'example']
a
example
9.11.5.2.2. Negative List Indices#
A negative index accesses elements from the end of the list counting backwards. The last element of any non-empty list is always li[-1]
. If the negative index is confusing to you, think of it this way: li[-n] == li[len(li) - n]
.
1li = ["a", "b", "zoom", "z", "example"]
2print(li)
3print(li[-1])
4
5# In this list, li[-3] == li[5 - 3] == li[2]
6print(li[-3])
['a', 'b', 'zoom', 'z', 'example']
'example'
'zoom'
9.11.5.2.3. Slicing a List#
You can get a subset of a list, called a slice by specifying two indices. The return value is a new list containing all the elements of the list, in order, starting with the first slice index up to but not including the second slice index.
If it helps, you can think of it this way: reading the list from left to right, the first slice index specifies the first element you want, and the second slice index specifies the first element you don’t want. The return value is everything in between.
1li = ["a", "b", "zoom", "z", "example"]
2print(li)
3
4# A slice of li[1] up to but not including li[3] will be created
5print(li[1:3])
6
7# Slicing works if one or both of the slice indices is negative.
8print(li[1:-1])
9
10# Lists are zero-based, so li[0:3] returns the first three elements of the list,
11# starting at li[0], up to but not including li[3].
12print(li[0:3])
13
14# If the left slice index is 0, you can leave it out, and 0 is implied. So li[:3]
15# is the same as li[0:3]
16print(li[:3])
17
18# Similarly, if the right slice index is the length of the list, you can leave it
19# out. So li[3:] is the same as li[3:5], because this list has five elements.
20print(li[3:])
21
22# If both slice indices are left out, all elements of the list are included.
23# li[:] is shorthand for making a complete copy of a list.
24print(li[:])
['a', 'b', 'zoom', 'z', 'example']
['b', 'zoom']
['b', 'zoom', 'z']
['a', 'b', 'zoom']
['a', 'b', 'zoom']
['z', 'example']
['a', 'b', 'zoom', 'z', 'example']
9.11.5.2.4. Adding Elements to Lists#
1li = ["a", "b", "zoom", "z", "example"]
2print(li)
3
4# Single elements can be added to the end of the list with append
5li.append("new")
6print(li)
7
8# insert inserts a single element into a list. The numeric argument is the index of the
9# first element that gets bumped out of position.
10li.insert(2, "new")
11print(li)
12
13# Lists can be concatenated with extend. Note that you do not call extend with multiple
14# arguments; you call it with one argument, a list. In this case, that list has two elements.
15li.extend(["two", "elements"])
16print(li)
['a', 'b', 'zoom', 'z', 'example']
['a', 'b', 'zoom', 'z', 'example', 'new']
['a', 'b', 'new', 'zoom', 'z', 'example', 'new']
['a', 'b', 'new', 'zoom', 'z', 'example', 'new', 'two', 'elements']
9.11.5.2.5. Difference between append und extend#
Lists have two methods, extend()
and append()
, that look like they do the same thing, but are in fact completely different. extend()
takes a single argument, which is always a list, and adds each of the elements of that list to the original list. On the other hand, append()
takes one argument, which can be any data type, and simply adds it to the end of the list.
1# extend method
2li = ['a', 'b', 'c']
3
4# li is extended with a list of another three elements ('d', 'e', and 'f'), so you
5# now have a list of six elements.
6li.extend(['d', 'e', 'f'])
7print(li)
8print(len(li))
9print(li[-1])
10
11#append method
12li = ['a', 'b', 'c']
13
14# append method is called with a single argument, which is a list of three elements
15# Now the list contains four elements because the last element appended is itself a
16# list. Lists can contain any type of data, including other lists.
17li.append(['d', 'e', 'f'])
18print(li)
19print(len(li))
20print(li[-1])
['a', 'b', 'c', 'd', 'e', 'f']
6
f
['a', 'b', 'c', ['d', 'e', 'f']]
4
['d', 'e', 'f']
9.11.5.2.6. Searching Lists#
1li = ['a', 'b', 'new', 'zoom', 'z', 'example', 'new', 'two', 'elements']
2print(li)
3
4# index finds (only) the first occurrence of a value in the list and returns the index
5print(li.index("example"))
6print(li.index("new"))
7
8# If the value is not found in the list, Python raises an exception.
9# To test whether a value is in the list, use in, which returns True if the value is
10# found or False if it is not.
11print(li.index("c"))
5
2
Traceback (most recent call last):
File "...", line ?, in ?
ValueError: 'c' is not in list
9.11.5.2.7. Deleting List Elements#
1li = ['a', 'b', 'new', 'zoom', 'z', 'example', 'new', 'two', 'elements']
2print(li)
3
4# remove (only) the first occurrence of a value from a list.
5li.remove("z")
6print(li)
7
8# removes only the first occurrence of a value
9li.remove("new")
10print(li)
11
12# pop removes the last element of the list, and it returns the value that it removed
13li.pop()
14print(li)
15
16# If the value is not found in the list, Python raises an exception.
17li.remove("c")
['a', 'b', 'new', 'zoom', 'z', 'example', 'new', 'two', 'elements']
['a', 'b', 'new', 'zoom', 'example', 'new', 'two', 'elements']
['a', 'b', 'zoom', 'example', 'new', 'two', 'elements']
['a', 'b', 'zoom', 'example', 'new', 'two']
Traceback (most recent call last):
File "...", line ?, in ?
ValueError: list.remove(x): x not in list
9.11.5.2.8. Using List Operators#
Lists can also be concatenated with the +
operator. list = list + otherlist
has the same result as list.extend(otherlist)
. But the +
operator returns a new (concatenated) list as a value, whereas extend only alters an existing list. This means that extend is faster, especially for large lists.
1li = ['a', 'b', 'zoom']
2li = li + ['example', 'new']
3print(li)
4
5# li += ['two'] is equivalent to li.extend(['two'])
6li += ['two']
7print(li)
8
9# The * operator works on lists as a repeater: li = [1, 2] * 3 is equivalent to
10# li = [1, 2] + [1, 2] + [1, 2], which concatenates three lists into one.
11li = [1, 2] * 3
12print(li)
['a', 'b', 'zoom', 'example', 'new']
['a', 'b', 'zoom', 'example', 'new', 'two']
[1, 2, 1, 2, 1, 2]
9.11.5.3. Tuples#
A tuple is an immutable list and can not be changed in any way once it is created. A tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets. The elements of a tuple have a defined order and the indices are zero-based, just like a list.
Tuples are faster than lists. If you’re defining a constant set of values and all you’re ever going to do with it is iterate through it, use a tuple instead of a list. Tuples can be converted into lists, and vice-versa. The built-in tuple function takes a list and returns a tuple with the same elements, and the list function takes a tuple and returns a list.
1t = ("a", "b", "mpilgrim", "z", "example")
2print(t)
3
4# The first element of a non-empty tuple is always t[0]
5print(t[0])
6
7# Negative indices count from the end of the tuple, just as with a list.
8print(t[-1])
9
10# Slicing works too, just like a list.
11print(t[1:3])
('a', 'b', 'mpilgrim', 'z', 'example')
a
example
('b', 'mpilgrim')
Keep in mind that tuples have not methods.
1t = ('a', 'b', 'mpilgrim', 'z', 'example')
2
3# all following examples cause errors
4# t.append("new")
5# t.remove("z")
6# t.index("example")
7
8# You can use "in" to see if an element exists in the tuple.
9"z" in t