This is part of an ongoing series on learning the Python programming language. If you haven't read them yet, I advise you to catch up on parts one, two, three, four, five, six, seven, eight and nine before reading this article.

In this blog post we'll learn about tuples and dictionaries, another two data structures.

Tuples

Tuples are a lot like lists, with one major distinction, they are immutable. This means that while you can change lists, you cannot change a tuple once it has been declared.

A tuple is declared using brackets and commas, similarly to lists.

primary_colours = ('red', 'blue', 'yellow')

There is one small catch when dealing with tuples and that is that because they use ordinary brackets if you want to declare a tuple with only one item you cannot just place that item in brackets, you need to add a comma to differentiate between just brackets and a tuple.

zero = ('0',)

As mentioned earlier, tuples cannot be changed, so those append, insert and other methods which we used with lists do not exist on tuples. All splicing operations still work because the spliced tuple is a copy of elements in the original tuple.

String Interpolation

Just a quick note before we continue to dictionaries, when constructing strings you can place the values of variables into a string by inserting a placeholder into the string at the position where you want the value inserted and appending those variables at the end of the string. This is called string interpolation. The variables at the end of the string need to be collected together in a tuple. After that long explanation, let's look at an example.

>>> fruitbowl = 'I have %d apples, %d bananas and %d pears.' % (num_apples, num_bananas, num_pears)
>>> print fruitbowl
I have 5 apples, 3 bananas and 2 pears.

You can read more about string interpolation and what those %d mean in the Python documentation on string formatting.

Dictionaries

A dictionary is a set of keys and associated values. You can think of a dictionary as an address book where you can find a person's contact details by looking up their name. While you can use other values for the keys in a dictionary, convention is to use strings.

Dictionaries are unordered structures, so never depend on having any order when working with them.

Dictionaries can be declared using braces like so:

features = {'os': 'Android', 'processor': 'ARM9'}

You can access and append or replace values in a dictionary by using the same index syntax as earlier, supplying the key instead of the position.

features['memory'] = '16G'
features['os'] = 'Android 4.1.2'
print features['os']

To remove a certain item from the dictionary, use the del keyword.

features['foo'] = 'bar'
del features['foo']

One of the nifty features of dictionaries is the ability to check if a key exists by using the in keyword.

if 'processor' in features:
    print features['processor']

To get a list of the keys or a list of the values, use the keys() and values() methods respectively.

>>> print features.keys()
['os', 'processor', 'memory']
>>> print features.values()
['Android 4.1.2', 'ARM9', '16G']

String Interpolation Revisited

String interpolation can be done using dictionaries too, but due to the nature of dictionaries, we have to specify the dictionary keys. Let's take a look.

>>> message = 'My tablet runs %(os)s, has an %(processor)s processor and %(memory)s of memory.' % features
>>> print message
My tablet runs Android 4.1.2, has an ARM9 processor and 16G of memory.

Note the "s" after the brackets. I still have to specify the variable type.

Practically Speaking

Lists, tuples and dictionaries are used all over the place in Python. A good understanding of how these data structures is quite essential to programming in Python. I've actually been fairly brief about them, due to time and space constraints, but you should be able to expand your understanding from here.

Have you got any cool examples of how to use data structures in Python?


Comments

comments powered by Disqus