GoConqr has a new look! Let us know what you think.

Flashcards

CS 111 Exam 3

Aqsa Arif English 39 cards

CS 111 Exam 3

Cards in this deck (39)

  1. 1DictionaryA dictionary is a Python container used to describe associative relationships. A dictionary is represented by the dict object type. A dictionary associates (or "maps") keys with values. A key is a term that can be located in a dictionary, such as the word "cat" in the English dictionary. A value describes some data associated with a key, such as a definition. A key can be any immutable type, such as a number, string, or tuple; a value can be any type.
  2. 2Example of DictA dict object is created using curly braces { } to surround the key:value pairs that comprise the dictionary contents. Ex: players = {'Lionel Messi': 10, 'Cristiano Ronaldo': 7} creates a dictionary called players with two keys: 'Lionel Messi' and 'Cristiano Ronaldo', associated with the values 10 and 7 (their respective jersey numbers). An empty dictionary is created with the expression players = { }.
  3. 3Accessing dictionary entriesUnlike a list, which orders elements according to a left-to-right positioning in a sequence, a dictionary's entries maintain no such ordering. To access an entry, the key is specified in brackets [ ]. If no entry with a matching key exists in the dictionary, then a KeyError runtime error occurs and the program is terminated.
  4. 4modifying dictionaryA dictionary is mutable, so entries can be added, modified, and deleted as necessary by a programmer. A new dictionary entry is added by using brackets to specify the key: prices['banana'] = 1.49. A dictionary key is unique – attempting to create a new entry with a key that already exists in the dictionary replaces the existing entry.
  5. 5deleting dictionary elementsThe del keyword is used to remove entries from a dictionary: del prices['papaya'] removes the entry whose key is 'papaya'.
  6. 6adding new elementsdict[k] = v: Adds the new key-value pair k-v, if dict[k] does not already exist.
    Example: students['John'] = 'A+'
  7. 7modifyingdict[k] = v: Updates the existing entry dict[k], if dict[k] already exists.
    Example: students['Jessica'] = 'A+'
  8. 8Removedel dict[k]: Deletes the entry dict[k].
    Example: del students['Rachel']
  9. 9what type is a dictionary?The dict type implements a dictionary in Python.
  10. 10making a dictionaryThe first approach wraps braces { } around key-value pairs of literals and/or variables: {'Jose': 'A+', 'Gino': 'C-'} creates a dictionary with two keys 'Jose' and 'Gino' that are associated with the grades 'A+' and 'C-', respectively.
    The second approach uses dictionary comprehension, which evaluates a loop to create a new dictionary, similar to how list comprehension creates a new list. Dictionary comprehension is out of scope for this material.
    Other approaches use the dict() built-in function, using either keyword arguments to specify the key-value pairs or by specifying a list of tuple-pairs. The following creates equivalent dictionaries:
    dict(Bobby='805-555-2232', Johnny='951-555-0055')
    dict([('Bobby', '805-555-2232'), ('Johnny', '951-555-0055')])
  11. 11dict operationsdict operations
  12. 12my_dict['Jason'] = ['B+', 'A-']['B+', 'A-'] is a list
  13. 13Dictionary MethodsA dictionary method is a function provided by the dictionary type (dict) that operates on a specific dictionary object. Dictionary methods can perform some useful operations, such as adding or removing elements, obtaining all the keys or values in the dictionary, merging dictionaries, etc.
  14. 14Modification of dictionary elements using the above methods is performed in-place. Ex: Following the evaluation of the statement my_dict.pop('Ahmad'), any other variables that reference the same object as my_dict will also reflect the removal of 'Ahmad'. As with lists, a programmer should be careful not to modify dictionaries without realizing that other references to the objects may be affected.Modification of dictionary elements using the above methods is performed in-place. Ex: Following the evaluation of the statement my_dict....
  15. 15my_dict['burger'] = my_dict['sandwich'] val = my_dict.pop('sandwich') print(my_dict['burger'])2.99 is printed
    Removing a key only removes that key and any shared reference to a value still exists.
  16. 16iterating over a dictionaryAs usual with containers, a common programming task is to iterate over a dictionary and access or modify the elements of the dictionary. A for loop can be used to iterate over a dictionary object, the loop variable being set to a key of an entry in each iteration. The ordering in which the keys are iterated over is not necessarily the order in which the elements were inserted into the dictionary. The Python interpreter creates a hash of each key. A hash is a transformation of the key into a unique value that allows the interpreter to perform very fast lookup. Thus, the ordering is actually determined by the hash value, but such hash values can change depending on the Python version and other factors.
  17. 17summoning certain typesThe dict type also supports the useful methods items(), keys(), and values() methods, which produce a view object. A view object provides read-only access to dictionary keys and values. A program can iterate over a view object to access one key-value pair, one key, or one value at a time, depending on the method used. A view object reflects any updates made to a dictionary, even if the dictionary is altered after the view object is created.
    dict.items() – returns a view object that yields (key, value) tuples.
    dict.keys() – returns a view object that yields dictionary keys.
    dict.values() – returns a view object that yields dictionary values.
  18. 18example of useexample of use
  19. 19solar_distances = dict(mars=219.7e6, venus=116.4e6, jupiter=546e6, pluto=2.95e9) list_of_distances = list(solar_distances.values()) # Convert view to list sorted_distance_list = sorted(list_of_distances) closest = sorted_distance_list[0] next_closest = sorted_distance_list[1]The dict.items() method is particularly useful, as the view object that is returned produces tuples containing the key-value pairs of the dictionary. The key-value pairs can then be unpacked at each iteration, similar to the behavior of enumerate(), providing both the key and the value to the loop body statements without requiring extra code.
  20. 20list nestingSince a list can contain any type of object as an element, and a list is itself an object, a list can contain another list as an element. Such embedding of a list inside another list is known as list nesting.Ex: The code my_list = [[5, 13], [50, 75, 100]] creates a list with two elements that are each another list.
  21. 21access to list within listsThe program accesses elements of a nested list using syntax such as
    my_list[0][0].
  22. 22multi-dimensional structuresA list is a single-dimensional sequence of items, like a series of times, data samples, daily temperatures, etc. List nesting allows for a programmer to also create a multi-dimensional data structure, the simplest being a two-dimensional table, like a spreadsheet or tic-tac-toe board. The following code defines a two-dimensional table using nested lists:
  23. 23iterating over a nested loop - use double for statementsAs always with lists, a typical task is to iterate through the list elements. A programmer can access all of the elements of nested lists by using nested for loops. The first for loop iterates through the elements of the outer list (rows of a table), while the nested loop iterates through the inner list elements (columns of a table). The code below defines a 3x2 table and iterates through each of the table entries:
  24. 24plotting and visualisingMany programs interact with sets of data, such as a list of ocean temperatures or daily calorie expenditure. A program can graphically plot, or visualize, such data.
  25. 25matplotlib - The matplotlib package can be used for plotting in Python. matplotlib replicates the plotting capability of MATLAB, an engineering-oriented programming language. matplotlib is short for "MATLAB plotting library."matplotlib is not required to be included in every Python distribution, but it is included in the Anaconda distribution of Python that we are using, so you don't need to download and install it. In fact, matplotlib (and NumPy) are included with almost all distributions of Python.
  26. 26open with and plottingopen with and plotting
  27. 27more on plottingThe program imports the pyplot module from the matplotlib package, renaming matplotlib.pyplot to plt using the as keyword. The as keyword renames an imported module or package. The program then reads the temperatures from a file and stores the temperatures in a list. The plt.show() function displays the graph.
    The plt.plot[a][b]() function plots data onto the graph. plot() accepts various arguments. Above, two lists are passed to the function: The years list is the x-coordinate of each point to plot, and the temps list is the y-coordinate. plot() combines the lists into (x, y) coordinates. Above, years[0] is 1850 and temps[0] is -0.1, so plot() draws a point at (1850, -0.1). The next coordinate is (years[1], temps[1]), or (1851, -0.7). plot() also draws a line between successive points.
    If provided just one list, as in plt.plot(temps), plot() uses 0, 1, ... for x values, as in (0, temps[0]), (1, temps[1]), etc.
  28. 28The below image shows the result when plot() is called twice. The first call plots ocean temperatures per year, and the second call plots the number of pirates (suggesting a correlation between rising ocean temperature and a decrease in piracy).The below image shows the result when plot() is called twice. The first call plots ocean temperatures per year, and the second call plots...
  29. 29plot stylingThe plot() function takes an optional format string argument that specifies the color and style of the plotted line. For example, plot(x_values, y_values, 'r--') uses 'r' to specify a red color, and '--' to specify a dashed line.
  30. 30using red dashusing red dash
  31. 31The below tables describe format string colors and styles. The default format string is 'b-' (solid blue line).The below tables describe format string colors and styles. The default format string is 'b-' (solid blue line).
  32. 32Format strings are a shortcut to setting line properties. A line property is an attribute of the line object created by matplotlib when plot() is called. Line properties determine how that line is displayed when show() is called.Format strings are a shortcut to setting line properties. A line property is an attribute of the line object created by matplotlib when p...
  33. 33more examplesmore examples
  34. 34The plt.legend() function displays a legend of the lines, using the label arguments passed to plot() as the text. Various keyword arguments can be given to customize the legend's appearance.The plt.legend() function displays a legend of the lines, using the label arguments passed to plot() as the text. Various keyword argumen...
  35. 35Text labels can help draw attention to interesting parts of a plot. Consider the plot below where a text label marks an important point on the x-axis.Text labels can help draw attention to interesting parts of a plot. Consider the plot below where a text label marks an important point o...
  36. 36The annotate() function creates an annotation that links a text label with a specific data point. The programmer specifies the coordinates of the text label and the data point, and an arrow is automatically drawn from text to data point.The first argument to annotate() is the label to display, which is placed at the coordinate described by xytext. Argument xy is the datapoint that the arrowhead points to. The arrow's appearance can be customized by passing a dictionary of arrow properties.The annotate() function creates an annotation that links a text label with a specific data point. The programmer specifies the coordinate...The annotate() function creates an annotation that links a text label with a specific data point. The programmer specifies the coordinate...
  37. 37Draw the string "Peak current" at coordinate (5, 10).plt.text(5, 10, 'Peak current')
  38. 38Annotate the data point at (100, 5), placing the text 'Peak current' at (115, 10).plt.annotate('Peak current', xy=(100, 5), xytext=(115, 10))
  39. 39—plt.annotate('Q1 Sales', xy=(4,2), xytext=(4,3))plt.annotate('Q1 Sales', xy=(4,2), xytext=(4,3))

Information

Description
Flashcards on CS 111 Exam 3, created by Aqsa Arif on 11/12/2019.
Created by
Aqsa Arif
Views
1
Rating

Feedback

What is it about?

What do you think of the new look?

How do you like it?