Skip to content

W6: Dictionaries, Sets, None and Sorting

Coming Up

  • Writing nice code
  • Dictionaries
  • Sets
  • None and sort() vs .sorted()

E1. Do the following code snippets do the same thing? What are some advantages and disadvantages of each snippet? What if we needed a hundred different types of tool?

Example A:

print("We need some saws")
print("We need some hammers")
print("We need some cogs")
print("We need some nails")

Example B:

def get_str(part):
    return f"We need some {part}"
print(get_str("saws"))
print(get_str("hammers"))
print(get_str("cogs"))
print(get_str("nails"))

Example C:

def get_str(part):
    return f"We need some {part}"
parts = ("saws", "hammers", "cogs", "nails")
for part in parts:
    print(get_str(part))

E2. Consider the following while loop and two conversions to for loops. Are the two for loops equivalent? Why might you choose one over the other?

Original While Loop:

count = 0
items = ('eggs', 'spam', 'more eggs')
while count < len(items):
    print(f"we need to buy more {items[count]}")
    count += 1

For Loop A:

items = ('eggs', 'spam', 'more eggs')
for count in range(len(items)):
    print(f"we need to buy more {items[count]}")

For Loop B:

items = ('eggs', 'spam', 'more eggs')
for item in items:
    print(f"we need to buy more {item}")

D2. What is the difference between using the .pop() method on a dictionary and using it on a list?

Sets

D3. In what situations would we use a โ€œsetโ€? How does it differ from other โ€œcontainersโ€ such as lists and dictionaries?

D4. What special operations can we perform on sets? How do we add and remove items from them?

E3. Evaluate the following given the assignment d = {"R": 0, "G": 255, "B": 0, "other": {"opacity": 0.6}}. Specify whether the value of d changes as a result. Assume d is reset to its original value each time.

E4. Evaluate the following given the assignment s1 = {1, 2, 4} and s2 = {3, 4, 5}. If s1 or s2 change as a result, give their new value. Assume s1 and s2 are reset to their original values each time.

Coding Problems

Problem 1

Write a function which takes a string as input and prints the frequency of each character in the string using a dictionary. freq_counts('booboo') should print:

b 2
o 4

Problem 2

Write a function which takes two lists as input and returns a list containing the numbers which they both have in common. in_common([1, 2, 4], [3, 4, 5]) should return [4].

Problem 3

Write a function which takes a dictionary and returns a sorted list containing the unique values in that dictionary. unique_values({'a': 1, 'b': 0, 'c': 0}) should return [0, 1].

Problem 4

Write a function which takes a string, a character and an integer threshold and returns True if the character appears in the string with a frequency above the threshold, False if it appears at or below the threshold, and None if it doesnโ€™t appear at all. above_thresh('I like the letter e', 'e', 3) should return True.