= {"Mercury":0.39, "Venus":0.72, "Earth":1.0, "Mars":1.5,"Jupiter":5.2,"Saturn":9.5, "Uranus":19.2,"Neptune":30.1, "Pluto": 39.5} orbitalRadii
6 Dictionaries and Sets
6.1 Dictionaries
6.1.1 Creating a Dictionary
A dictionary is a multi-element object just like a list or tuple but instead of connecting each element to an integer index value, a keyword is used. Dictionaries allow you to access data without knowing anything about the order of the items. For example, maybe you want to store the orbital radius of all the planets in the solar system. Using a dictionary you can associate the name of the planet with its orbital radius. A string containing the planet’s name could serve as the key and the associated radius as the value.
Dictionaries are built using curly braces ({}
) instead of square brackets (lists) or parentheses (tuples). Each item in the dictionary is a key:value
pair and the items are separated by commas just like lists. Below is an example
The keys don’t have to be strings, but can be any data type. For example, maybe you’d like the keys to be the orbital radii of the planets and the values to be the associated orbital period (in Earth days).
= {0.39: 88, 0.72: 224.7 , 1.0: 365.2 , 1.5: 687 ,5.2: 4331 ,9.5: 10_747 , 19.2: 30_589 ,30.1: 59_800 ,39.5: 90_560 } radiiandPeriod
Accessing an element of a dictionary is done with square brackets ([]
) just like lists, but instead of placing an integer index the key value is used.
= {"Mercury":0.39, "Venus":0.72, "Earth":1.0, "Mars":1.5,"Jupiter":5.2,"Saturn":9.5, "Uranus":19.2,"Neptune":30.1, "Pluto": 39.5}
orbitalRadii
= orbitalRadii["Jupiter"] jupiterRadius
To Do:
- Use a print statement to verify that the correct orbital radius was extracted.
- Can you extract the orbital radius of Pluto from the list?
Additional key:value
pairs can be added to an existing dictionary by calling the key and assigning it to a value
= {"Mercury":0.39, "Venus":0.72, "Earth":1.0, "Mars":1.5,"Jupiter":5.2,"Saturn":9.5, "Uranus":19.2,"Neptune":30.1, "Pluto": 39.5}
orbitalRadii
"Moon"] = 0.384 orbitalRadii[
6.1.2 keys
, items
and values
methods
Three dictionary methods are so heavily used that they are worth mentioning here. The keys
method will return a list1 of all keys that are present in the dictionary. The values
method will return a list of all values present in the list and the items
method will return a nested list containing all key:value pairs.
1 Actually it produces an iterator that can be used in conjunction with a loop. If you want a list you must use the list
function.
= {"Mercury":0.39, "Venus":0.72, "Earth":1.0, "Mars":1.5,"Jupiter":5.2,"Saturn":9.5, "Uranus":19.2,"Neptune":30.1, "Pluto": 39.5}
orbitalRadii
= orbitalRadii.values()
vals = orbitalRadii.keys()
keys = orbitalRadii.items() items
To Do:
- Use print statements in the cell above to see what the
keys
,items
, andvalues
methods produce.- Ask questions as needed.
6.1.3 Other useful dictionary methods
There are a few other useful dictionary methods worth mentioning and I’ll place them in the cell below so that you can investigate what they do.
= {"Mercury":0.39, "Venus":0.72, "Earth":1.0, "Mars":1.5,"Jupiter":5.2,"Saturn":9.5, "Uranus":19.2,"Neptune":30.1, "Pluto": 39.5}
orbitalRadii
= {"Moon":0.384, "Venus": 0.71}
radii "Mercury")
orbitalRadii.pop(
orbitalRadii.popitem()= dict.fromkeys(["Mercury", "Venus", "Earth"])
oRadii print(oRadii)
orbitalRadii.update(radii)
{'Mercury': None, 'Venus': None, 'Earth': None}
To Do:
- Use print statements to determine what each dictionary method in the cell above does.
- Add comments next to each line explaining the method.
6.2 Sets
A set is another python data type that is used occasionally. They are multi-element objects similar to lists and tuples with one key difference: there can be no repeated elements in a set.
6.2.1 Creating a Set
Sets are created using curly braces ({}
) just like dictionaries but instead of placing key:value
pairs inside, single values are used. Any repeated elements will be automatically deleted when the set is created.
= {1,2,4,2,1,3,4} mySet
To Do:
- Predict what the set defined above will contain.
- Use a print statement to check yourself and adjust your thinking as needed.
The set
function can be used to turn a list or tuple into a set and any repeated elements will be deleted. This can be a handy way to remove unwanted duplicates from a list.
= ["H", "He", "Ne", "He", "N", "Ag", "Pt", "Ag"]
elements
= set(elements)
mySet
print(mySet)
{'Pt', 'N', 'Ag', 'Ne', 'H', 'He'}
6.2.2 Modifying a set
Elements can be added to a set using the add
and/or update
methods. The add
method will add a single element to the set and update
will allow you to add more than one element.
= {"H", "He", "Ne", "He", "N", "Ag", "Pt", "Ag"}
elements
"Au")
elements.add(
"In","Cu","Os","He"]) elements.update([
To Do:
- Predict what the set will look like after the
add
method executes. Then add a print statement to verify that you’re correct.
- What happens if you try to
add
an element that is already in the set?- Predict what the set will look like after the
update
method executes. Then add a print statement to verify that you’re correct.
Elements can be removed from a set using the remove
and/or discard
methods. The difference between these methods is very subtle. They will both remove an element, but the remove
method will throw an error if the element you are attempting to remove isn’t in the set. discard
won’t throw an error even if the element isn’t present. The clear
method will remove all entries from the set.
= {"H", "He", "Ne", "He", "N", "Ag", "Pt", "Ag"}
elements
"H")
elements.remove("He")
elements.discard("Cu")
elements.discard("Cu")
elements.remove( elements.clear()
To Do:
Predict what the set will look like after each statement in the cell above. Then add a print statement to verify that you’re correct.
6.2.3 Mathematical Set Operations
Sets are a well-known mathematical idea and there are four mathematical operations that are commonly used with sets. They are: union, intersection, difference, and symmetric difference. We’ll investigate them one at a time.
6.2.3.1 Union
The union of two sets is the set of all unique elements between both sets. The union of two sets can be found using the |
operator.
= {1,1,2,3,5,8,13,21,34,55,89,147,236}
fibonacci = {1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190}
triangles
= fibonacci|triangles union
6.2.3.2 Intersection
The intersection of two sets is the set of elements that are common to both sets. The intersection of two sets can be found using the &
operator
= {1,1,2,3,5,8,13,21,34,55,89,147,236}
fibonacci = {1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190}
triangles
= fibonacci&triangles intersect
6.2.3.3 Difference and Symmetric Difference
And finally, the difference of two sets is the set of elements that are found in one set but not in the other. The difference of two sets can be found using the -
operator. Note that A - B
will produce a different set than B - A
. A- B
will produce a set with all of the elements from set A
that are not in set B
. B - A
will do just the opposite, forming a set with all the elements from set B
that are not in set A
. If you want the set of elements that are in A
and B
but not in both (kind of like the opposite of intersection) then you want the symmetric difference operator (^
)
= {1,1,2,3,5,8,13,21,34,55,89,147,236}
fibonacci = {1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190}
triangles
= fibonacci - triangles
diff = triangles - fibonacci
diffTwo = fibonacci ^ triangles symdiff
To Do:
- Predict what the set will look like after each statement in the cells above.
- Add print statements to check yourself.
As a final point you should note that set elements cannot be extracted using square brackets like you can with lists and tuples. It’s just not allowed. However, you can iterate over sets even though there is no guarantee about the order they will come in. We’ll see what it means to iterate when we study loops.
= {"Li","Be","B", "C","N", "O","F", "Ne"}
elements
print(elements[2])