6  Dictionaries and Sets

Jupyter Notebook

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

orbitalRadii = {"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}

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).

radiiandPeriod = {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 }

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.

orbitalRadii = {"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}

jupiterRadius = orbitalRadii["Jupiter"]

To Do:

  1. Use a print statement to verify that the correct orbital radius was extracted.
  2. 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

orbitalRadii = {"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  

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.

  • orbitalRadii = {"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}
    
    vals = orbitalRadii.values()
    keys = orbitalRadii.keys()
    items = orbitalRadii.items()

    To Do:

    1. Use print statements in the cell above to see what the keys, items, and values methods produce.
    2. 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.

    orbitalRadii = {"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}
    
    radii = {"Moon":0.384, "Venus": 0.71}
    orbitalRadii.pop("Mercury")
    orbitalRadii.popitem()
    oRadii = dict.fromkeys(["Mercury", "Venus", "Earth"])
    print(oRadii)
    orbitalRadii.update(radii)
    {'Mercury': None, 'Venus': None, 'Earth': None}

    To Do:

    1. Use print statements to determine what each dictionary method in the cell above does.
    2. 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.

    mySet = {1,2,4,2,1,3,4}

    To Do:

    1. Predict what the set defined above will contain.
    2. 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.

    elements = ["H", "He", "Ne", "He", "N", "Ag", "Pt", "Ag"]
    
    mySet = set(elements)
    
    print(mySet)
    {'H', 'Ag', 'N', 'Pt', 'Ne', '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.

    elements = {"H", "He", "Ne", "He", "N", "Ag", "Pt", "Ag"}
    
    elements.add("Au")
    
    elements.update(["In","Cu","Os","He"])

    To Do:

    1. Predict what the set will look like after the add method executes. Then add a print statement to verify that you’re correct.
    2. What happens if you try to add an element that is already in the set?
    3. 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.

    elements = {"H", "He", "Ne", "He", "N", "Ag", "Pt", "Ag"}
    
    elements.remove("H")
    elements.discard("He")
    elements.discard("Cu")
    elements.remove("Cu")
    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.

    fibonacci = {1,1,2,3,5,8,13,21,34,55,89,147,236}
    triangles = {1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190}
    
    union = fibonacci|triangles

    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

    fibonacci = {1,1,2,3,5,8,13,21,34,55,89,147,236}
    triangles = {1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190}
    
    intersect = fibonacci&triangles

    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 (^)

    fibonacci = {1,1,2,3,5,8,13,21,34,55,89,147,236}
    triangles = {1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190}
    
    
    diff = fibonacci - triangles
    diffTwo = triangles - fibonacci
    symdiff = fibonacci ^ triangles

    To Do:

    1. Predict what the set will look like after each statement in the cells above.
    2. 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.

    elements= {"Li","Be","B", "C","N", "O","F", "Ne"}
    
    print(elements[2])

    6.3 Flashcards

    1. Describe all of the ways that you can make a dictionary.
    2. Describe all of the ways that you can make a set.
    3. How do you add a new key:value pair to a dictionary?
    4. How do you add a new value to a set?
    5. What does the keys dictionary method produce?
    6. What does the values dictionary method produce?
    7. What does the items dictionary method produce?
    8. What does the union operator (|) do?
    9. What does the intersection operator (&) do?
    10. What does the difference operator (-) do?
    11. What does the symmetric difference operator (^) do?
    12. Where is the record of The Savior’s visit to the American continent?

    6.4 Exercises

    1. (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.
    1. (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{ 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:

    1. \(5\) miles to meters.
    2. \(250^\circ\) to radians.
    3. \(562\) Joules to electron-volts.
    4. \(3500\) inches to meters.
    5. \(5.8\) m\(^3\) to cm\(^3\).
    conversions = {"km-to-m": 1000, "in-to-cm": 2.54 }
    1. 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. Once the dictionaries are created, verify that you can extract values from them as you would expect.
    # Python code here.
    1. 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:

      1. The average of the property that you chose.
      2. The largest values.
      3. The smallest value.
    # Python code here.
    1. In the cell below you will find the first 15 numbers for several important mathematical sequences. Answer the following questions:

      1. Find all of the numbers that are in the fibonacci sequence and the triangles sequence. (intersection)
      2. Find all of the numbers that are in the pentagonal sequence but not in the hexagonal sequence. (difference)
      3. Find the union of the fibonacci sequence and the hexagonal sequence and report how many numbers there are.
      4. Determine how many numbers are in the caterer sequence but not in the hexagonal sequence.
    fibonacci = {1,1,2,3,5,8,13,21,34,55,89,147,236,383,619}
    squares= {1,4,9,16,25,36,49,64,81,100,121,144,169,196,225}
    triangles = {1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190}
    pentagonal = {1, 5, 12, 22, 35, 51, 70, 92, 117, 145, 176, 210, 247, 287, 330}
    hexagonal = {1, 6, 15, 28, 45, 66, 91, 120, 153, 190, 231, 276, 325, 378, 435}
    caterer = {2, 4, 7, 11, 16, 22, 29, 37, 46, 56, 67, 79, 92, 106, 121}