= {"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)
{'Ne', 'H', 'Ag', 'Pt', 'N', '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])
6.3 Flashcards
- Describe all of the ways that you can make a dictionary.
- Describe all of the ways that you can make a set.
- How do you add a new
key:value
pair to a dictionary? - How do you add a new value to a set?
- What does the
keys
dictionary method produce? - What does the
values
dictionary method produce? - What does the
items
dictionary method produce? - What does the union operator (
|
) do? - What does the intersection operator (
&
) do? - What does the difference operator (
-
) do? - What does the symmetric difference operator (
^
) do? - Where is the record of The Savior’s visit to the American continent?
6.4 Exercises
(Physical Constants) The field of physics is filled with experimental constants. In fact, you’ll use some of them so frequently throughout your undergraduate experience that you’ll end up memorizing them. Until then it could be useful to store some of these constants in a dictionary for easy reference. Choose at least 15 constants from the following website and build a dictionary of them. Make sure that the following constants are in your list: \(k_B\), \(\hbar\), \(c\), \(e\), and \(\epsilon_0\). You are free to choose the names of the keys to be anything that makes good sense to you.
Then use your dictionary to calculate the following values \[\sigma = {\pi^2 k_B^4 \over 60 \hbar^3 c^2} \text{ (Stefan-Boltzmann constant)}\] \[\alpha = {e^2 \over 4 \pi \epsilon_0 \hbar c} \text{ (fine-structure constant)}\]
# Python code here.
- (Unit Conversions) Unit conversions show up all over in physics and if you don’t have the conversion factors memorized you may find yourself constantly looking them up. Construct a dictionary that contains many of the most useful unit conversions, including those shown below. You are free to choose the key names to be whatever makes most sense to you. I’ve given a few examples in the code cell below to get you started. \[ 1 \text{ kilometer} = 1000 \text{ meters}\] \[ 1 \text{ meter} = 100 \text{ centimeters}\] \[ 1 \text{ inch} = 2.54 \text{ centimeters}\] \[ 1 \text{ mile} = 1.609 \text{ kilometers}\] \[ 1 \text{ mph} = 0.447 \text{ m/s}\] \[ 1 \text{ u} = 1.661 \times 10^{-27} \text{ kg}\] \[ 1 \text{ electron-volt} = 1.602 \times 10^{-19} \text{ Joules}\] \[ 1 \text{ day} = 24 \text{ hours}\] \[ 1 \text{ radian} = 57.3^\circ\] \[ 1 \text{ rev} = 2\pi \text{ radians}\]
Once the dictionary is created use it to perform the following conversions:
- \(5\) miles to meters.
- \(250^\circ\) to radians.
- \(562\) Joules to electron-volts.
- \(3500\) inches to meters.
- \(5.8\) m\(^3\) to cm\(^3\).
= {"km-to-m": 1000, "in-to-cm": 2.54 } conversions
- Here you will find a table containing planetary information. Pick your top three favorite planets and make one dictionary for each planet. The keys in the dictionary should be the row label from the table (or a shortened version of that label) and the item value should be the number in the table. Pick 10 rows in the table to put in your dictionary. Once the dictionaries are created, verify that you can extract values from them as you would expect.
# Python code here.
Here you will find a table containing planetary information. Pick a row from the table and make a dictionary that holds the values in that row. The keys to the dictionary should be the planets and the values are the value from the table. Once the dictionary is created, use it to calculate the following:
- The average of the property that you chose.
- The largest values.
- The smallest value.
# Python code here.
A dictionary can be used to represent a polynomial. The dictionary keys are the exponents and the values are their corresponding coefficients. For example the dictionary
{2:3,1:-2,0:1}
would represent the polynomial \(3x^2 - 2x + 1\).- Represent the following polynomials as dictionaries: \(5x^3 - 8x^2 + 2x -5\) and \(4x^2 + 16x - 9\)
- Use the dictionaries to add up the polynomials.
- Print the result to screen.
# Python code here.
(Prime Factorization) Prime factorization is a way to represent a number as a product of it’s prime factors. For example, the prime factorization of \(50\) is \(2 \times 5 \times 5\). This factorization can be represented in a dictionary by placing the prime number as the dictionary keys and the values as the number of times that prime appears in the factorization. For our example of \(50\), this dictionary would be
{2:1,5:2}
.- Build the prime-factorization dictionary for the following numbers: 50,66,78,45 (Just perform the factorization manually; coding it would require a loop.)
- Now write some code to calculate the original numbers from their dictionary representation.
# Python code here.