Sets And Maps in Python

A set is a data structure that holds elements in no particular order. An efficient back-end data structure for sets is the hash map. In python, sets can be defined using curly braces

In [1]:
x = {2, 8, 3}
print(x)

Set containment works with the in command

In [2]:
print(8 in x)
print(10 in x)

We can add elements to sets with the add command

In [3]:
x.add(5)
print(x)

We can remove elements with the remove command

In [4]:
x.remove(3)
print(x)

If we add an element that's already there, it doesn't change the set

In [5]:
x.add(8)
print(x)

Map

A map is just like a set, except there is an associated value with every element. The lookup element is referred to as the key. We can think of a map like a dictionary where the key is the word and the value is the definition. In fact, python calls their version of a map a "dictionary" for this very reason. Python dictionaries can also be defined with curly braces, except we specify both a key and a value with the key:value syntax

In [8]:
people = {"chris":31, "celia":31, "theo":8, "layla":9}

We can check to see if a key is there, just as we did with a set

In [9]:
print("chris" in people)
print("nick" in people)
True
False

We can also add elements, though the syntax is slightly different and looks more like array syntax; the key is in brackets, and the value is on the right hand side of an assignment

In [11]:
people["nick"] = 100
print(people)
{'chris': 31, 'celia': 31, 'theo': 8, 'layla': 9, 'nick': 100}
In [ ]: