Lesson 11 - Tuples, sets, and dictionaries in Python

Python Basics Tuples, sets, and dictionaries in Python

In the previous lesson, Multidimensional lists in Python, we went over lists in the Python programming language. In today's tutorial, we'll go over tuples, sets, and dictionaries.

Tuples

Tuples are very similar to lists. They're sequences, but their items cannot be modified. We declare them using parentheses:

items = (1, 2, 3, 7)
print(items)

The output:

Console application
(1, 2, 3, 7)

There is a little catch when it comes to declaring a tuple with a single item. We have to use a comma after the item to distinguish it from an ordinary expression in parentheses:

number = (1)
items = (1,)
print(number)
print(items)

The output:

Console application
1
(1,)

As you might expect, we use tuples when we need to pass a sequence somewhere and we want to make sure it isn't changed accidentally. In order to modify a tuple, since they're read-only, you have to create a new one with the items set to whatever you need. This can be done, for example, by converting a tuple to a list and then back:

items = (1, 2, 3, 7)
print(items)
items_as_list = list(items)
items_as_list[1] = 4
items = tuple(items_as_list)
print(items)

The result:

Console application
(1, 2, 3, 7)
(1, 4, 3, 7)

Notice the tuple() method which converts other sequences to tuples. Tuples can also be merged together with other tuples using the + operator. This applies to any and every type of sequence:

grades_january = ('A', 'A', 'D', 'B')
grades_february = ('F', 'C', 'A')
grades = grades_january + grades_february
print(grades)

The result:

Console application
('A', 'A', 'D', 'B', 'F', 'C', 'A')

We could do the same with 2 lists. However, as you probably know, it won't work with tuples and lists without converting one to the other explicitly.

We use the len() function to ask about the number of elements and we can also use the min() and max() functions (just like with every other Python sequence). We can also use the in operator, the for loop, [] for indexing, and so on.

Sets

Sets are also similar to lists, but they only contain unique items and they're unordered, meaning that the item order is not maintained and can change unpredictably. As you may have guessed, this is also the mathematical definition of a set. There is no special syntax for sets as there was for lists and tuples. We create them simply by using the global set() function and passing any other sequence to it:

planets = set(("Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"))
print(planets)
planets.add("Pluto")
print(planets)
planets.add("Neptune")
print(planets)

The output:

Console application
{'Saturn', 'Mars', 'Uranus', 'Earth', 'Jupiter', 'Neptune'}
{'Pluto', 'Saturn', 'Mars', 'Uranus', 'Earth', 'Jupiter', 'Neptune'}
{'Pluto', 'Saturn', 'Mars', 'Uranus', 'Earth', 'Jupiter', 'Neptune'}

We created a set of 6 planet names. Notice the double parentheses on the line with the set() function. You should've noticed that we're passing a tuple as the function parameter. As you can see, the item order is not preserved and it changed immediately after the declaration. This is not a flaw, the items are internally kept in the order which helps the set determine if the elements are unique efficiently.

Set methods

add()

We add set items using the add() method. As you can see in the code above, if we try to add an element which is already there, no error is thrown, it just isn't added.

difference() and difference_update()

As you might expect, the set provides all the set operations we know from math classes. We can ask for the difference between 2 sets. The difference() method returns the difference between 2 sets as a new set. difference_update() modifies the set and removes all the elements from the other set (set subtraction).

remove(), discard(), and, pop()

All 3 of these methods remove an element from the set. Remove() throws an error if the given element is not there. Alternatively, discard() would do the same thing, but without throwing an error. Pop() removes a value from the set and returns it.

intersection()

We can compute the intersection for 2 sets using the intersection() method.

isdisjoint()

Determines whether two sets have no intersection (no common items).

issubset() and issuperset()

We can ask whether the set is a subset (all its elements are present in the other set) or a superset (all the elements of the other set are present within it) using the issubset() and the issuperset() method.

clear()

This method removes all the elements from the set.

Dictionaries

Dictionaries work similar to lists. However, item indexes are not only numeric, they're also strings or any other immutable types. We refer to dictionary indexes as keys. The order of the items is not preserved. They're ordered in a way that's efficient for us to access them through their keys and there is no way to maintain any custom order.

We declare a dictionary just like a list, the main difference being that we use curly braces and we have to define their keys as well. We use a colon (:) operator to do so:

favorite_things = {
        'homer': 'donuts',
        'marge': 'ovens',
        'bart': 'slingshots',
        'lisa': 'books',
}

We formatted the dictionary declaration in multiple lines to improve readability, but we could write it on a single line as well. There are 4 values in the dictionary: 'donut', 'oven', 'slingshot', 'book'. Each value belongs to a key ('homer', marge', 'bart', 'lisa'). We use colons to associate each value to its key and separate them with commas. I left a comma after the last value as well so that I wouldn't forget to add it later on (this is a great habit and I implore you to do so).

By the way, notice that we use the under_score notation when we created a variable whose name consists of two or more words. The first letter is lowercase and words are separated by underscores (_).

We can work with dictionaries in the same as we did previously with lists:

print('Homer likes ' + favorite_things["homer"])

The output:

Console application
Homer likes donuts

Instead of writing favorite_things[0], we use the string key. The main advantage to using dictionaries is better readability. We actually see what we're getting off a list. Whereas with numeric indexes, we may not even know what the value is.

Each key has to be unique, the values don't have to. Both keys and values can be of any immutable data type. If we define the same key in the same dictionary multiple times and with different values, the last value will be assigned to the key.

Adding items

We can easily add new items by assigning values under new keys:

favorite_things['maggie'] = 'dolls'
print('Homer likes: ' + favorite_things["homer"])
print('Maggie likes: ' + favorite_things["maggie"])

The same applies to modifying the values.

To determine the number of items in a dictionary, we use the global len() function like we did with lists:

print('Items: %d' % (len(favorite_things)))

We use the in operator to ask whether a certain key is in the dictionary. In Python 2.x, we had the has_key() method, which is now deprecated.

simpson = input("Hello! What is your favorite character in the Simpsons, you may only choose from the core family members: ")
if simpson in favorite_things:
        print("%s likes %s." % (simpson.lower(), favorite_things[simpson]))
else:
        print("Hey! That's not a Simpson!")

The output:

Console application
Hello! What is your favorite character in the Simpsons, you may only choose from the core family members: Krusty
Hey! That's not a Simpson!

Dictionary methods

Similar to lists, there are several methods available for dictionaries. Let's go over the most important ones.

get()

Another way to access dictionary items is using the get() method. The main advantage to this is that it doesn't throw an exception if the given key isn't there. Instead, it returns None or any default value we specify as the second parameter:

print(favorite_things.get('homer'))
print(favorite_things.get('krusty'))
print(favorite_things.get('krusty', 'nobody'))

The output:

Console application
donut
None
nobody
values(), keys(), and items()

We can convert a dictionary to lists of their values, keys, or even to lists of the tuples of their key-value pairs:

print(favorite_things.values())
print(favorite_things.keys())
print(favorite_things.items())

The output:

Console application
dict_values(['book', 'doll', 'slingshot', 'oven', 'donut'])
dict_keys(['lisa', 'maggie', 'bart', 'marge', 'homer'])
dict_items([('lisa', 'book'), ('maggie', 'doll'), ('bart', 'slingshot'), ('marge', 'oven'), ('homer', 'donut')])
clear()

As the method name suggests, it clears all the items in a dictionary.

In the next lesson, Importing modules and the math module in Python, we're going to get familiar with importing Python modules and learn about the math module.


 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Activities (5)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!