Programming with Python: How to Program Dictionaries, Tuples and Sets with Python

Programming with Python: How to Program Dictionaries, Tuples and Sets with Python
Page content

Tuples

Now you know about lists, lets look at, the rather odd structure, tuples. They can be used to store n bits of data. You can pack many values in a tuple and unpack them later. For example storing pairs of coordinates together.

The elements of a tuple are listed between parenthesis (), and are assigned to a variable - This is packing the tuple. When you want the values extracted from inside the tuple, you unpack it. Assign the variables that will receive the individual values between the parenthesis (), but this time you perform the assignment by putting the values on the left and the variable name on the right.

..

Image by openpeta.com

human = (‘Josef’, ‘Nankivell’, ‘1987’) # pack

print human

(firstname, surname, dob) = human # unpack

print firstname # outputs ‘Josef’

Dictionaries

Dictionaries store values that can be accessed using a key, either numerical or a string. A key is selected arbitrarily - Unlike an array you do not need to use incremental indices to point to each element.

First, we have to initialize a dictionary. In this case, we will store the birth year of people - this is known as stringent mapping.

The key & value pairs are listed between curly brackets " { } “, then we query the dictionary using square brackets " [ ] “.

dob={‘Joe’:1987, ‘Bob’:1964}

print dob[‘Joe’]

# returns ‘1987’

Another option is to start with an empty dictionary and then assign the values later.

dob={}

dob[‘Joe’] = 1987

dob[‘Bob’] = 1964

Even with an empty dictionary, you have to create the dictionary before adding values, do this by: dictionary_name={}. An exception would be thrown if you were to try to assign values to a non-existent dictionary.

Existing values can be altered, just reassign the new value to the existing key.

dob[‘Bob’] = 1963

print dob[‘Bob’]

# displays ‘1963’

Tto display the contents of a dictionary, a simple print works fine.

print dob

# returns: {‘Joe’: 1987, ‘Bob’: 1963}

To delete elements, just use the del statement.

del dob[‘Bob’]

print dob

# returns’{‘Joe’: 1987}’

Sets

Everyone should be familiar with sets from mathematics. If not, a set is a pile of unordered, non-duplicated elements.

Sets need initialized with the elements of a list. As you now know what a list is, this can be done simply. Again, print can handle a set as it is.

Once a set is created we can perform the most useful feature of sets - testing whether an element exists:

shopping_list=set([‘cheese’, ‘milk’, ‘beef’])

print shopping_list

# returns set([‘cheese’, ‘milk’, ‘beef’])

print ‘milk’ in shopping_list

# returns ‘True’

Sets are only interesting if we have more that one of them! With two sets we can see the elements that both sets contain, this is called an “intersection”.

christmas_shopping_list=set([‘crackers’, ‘beef’, ‘pudding’, ’tree’])

print shopping_list & christmas_shopping_list

# returns ‘set([‘beef’])’

Also, we can perform the union of sets ( | ), difference ( - ), or symmetric difference ( ^ ).

That’s pretty much it for sets, using the above examples you can do anything. For example, add a new element, you can use union.

shopping_list = shopping_list | set([‘biscuits’])

Conclusion

I hope you enjoyed this brief introduction to Programming Python in Linux. Once you get a firm grasp on it, you’ll be able to code your tasks using this efficient language in a very short time.

The past few articles should get you started with Python, however, there is a lot more ground to cover yet, loops, exceptions & even creating some working programs!

This post is part of the series: A Guide to Linux Programming with Python

Python is a very useful language, whether you need a little script that edits files or want to create a bigger project. Python has all the power you need, including testing, modularization, object-orientation and a massive API. This series will let you get your hands dirty with Python and Linux.

  1. A Guide to Linux Programming with Python
  2. A Guide to Linux Programming with Python - Variables & Data Structures
  3. A Guide to Linux Programming with Python - Tuples, Dictionaries and Sets