my_dict = {
"name": "John",
"age": 25,
"city": "New York",
"is_student": False
}
for p in my_dict:
print("key: ", p, " had value ", my_dict[p])
Solution:
key: name had value John
key: age had value 25
key: city had value New York
key: is_student had value False
[14.4] Trace the following code. What happens in each line?
1. d = { 26: "Chen", 23: "Patrick" }
2. d[88] = "Rosa"
3. d[23] = "Pat"
4. d[51] = d[23]
5. if "Chen" in d:
6. d.pop("Chen")
Solution:
Line 1. The dictionary with two key-value pairs is created
Line 2. We create a new key value pair 88-"Rosa" and add it to d
Line 3. We update the existing key 23 to be associated with the value Pat. The dictionary now hold 23:"Pat" instead of 23:"Patrick"
Line 4. A new key 51 is added with the value "Pat", which is associated with key 23. So 51:"Pat" will be added to the dictionary.
Line 5. Checks if the key "Chen" is in the dictionary. Because there is no key "Chen" (only a value), we do not enter the if condition, and no element is poped.
[14.5] What does the following code do?
def mystery(d):
total = 0
for key in d:
total = total + d[key]
return total
Solution: The mystery function iterates over the keys in the dictionary. For each key, it adds the value associated with that key (d[key]) to a total variable. Namely, it adds all the values in the dictionary. In the end, the function returns the total sum.
Code Writing
[14.6] Write a line of code to do the following:
a. make an empty dictionary (call it d1)
b. make a dictionary mapping strings to integers (call it d2)
c. print the length of the d2
d. add a new key-value pair to d2
e. update a key-value pair in d2
f. remove a key-value pair in d2
Solution:
a. d1 = {}
b. d2 = {"apples": 3, "pears": 4}
c. print(len(d2))
d. d2["bananas"] = 7
e. d2["apples"] = d2["apples"] + 1
f. d2.pop("pears")
[14.7] Write a function that takes a string as input and returns a dictionary with the count of each word in the string.
Solution:
def word_frequency_counter(input_string):
word_count = {}
words = input_string.split()
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
s = "they already know what my favorite ice-cream is, my favorite ice-cream is vanilla"
print(word_frequency_counter(s))
[14.8] Create a function that inverts the keys and values of a given dictionary.
Solution:
def invert_dictionary(input_dict):
inverted_dict = {}
for key in input_dict:
value = input_dict[key]
inverted_dict[value] = key
return inverted_dict
print(invert_dictionary({"a":2, "b":3, "c":4}))
[14.9] Write a function that takes two dictionaries of the same size as input and returns a new dictionary containing only the common key-value pairs.
Solution:
def common_elements(dict1, dict2):
common_dict = {}
for key in dict1:
if key in dict2 and dict1[key] == dict2[key]:
common_dict[key] = dict1[key]
return common_dict
print(common_elements({"a":2, "b":3, "c":4}, {"f":4, "a":2,"c":4}))
[14.10] Write a function that merges two dictionaries, summing the values for common keys.
Solution:
def merge_dictionaries(dict1, dict2):
merged_dict = {}
# copy one dictionary to the merged dictionary
for key in dict1:
value = dict1[key]
merged_dict[key] = value
# iterate over dict2
# if the key is in merged_dict, update it
# otherwise add it as a new key-value pair
for key in dict2:
value = dict2[key]
if key in merged_dict:
merged_dict[key] = merged_dict[key] + value
else:
merged_dict[key] = value
return merged_dict
print(merge_dictionaries({"a":2, "b":3, "c":3},{"c":4, "a":4, "d":1}))
[14.11] Create a function that searches for a key based on a given value in a dictionary. The function returns the key if it finds it or None otherwise. Assume the values are unique.
Solution:
def find_key_by_value(input_dict, target_value):
for key in input_dict:
value = input_dict[key]
if value == target_value:
return key
return None # Return None if the value is not found
print(find_key_by_value({"a":2, "b":3, "c":4, "d":7}, 4))
[14.12] Write a function that given a dictionary of string-number pairs, create a new dictionary that includes only the pairs where the number values are negative. ssume the number values could be either negative or positive.
Solution:
def filter_negative_values(input_dict):
negative_dict = {}
for key in input_dict:
if input_dict[key] < 0:
negative_dict[key] = input_dict[key]
return negative_dict
print(filter_negative_values({"a":-5, "b":2, "c":3, "g":-10, "h":-99}))
[14.13] Create a function countChar that takes in a string and returns a dictionary that maps the frequency of how many times a character appears. Treat lowercase and uppercase chars as the same
Solution:
def countChar(s):
d = {}
for c in s.lower():
if c in d:
d[c] +=1
else:
d[c] = 1
return d
#Example usage:
print(countChar("hello World oooOOOOoo"))
[14.14] Given a dictionary of strings to numbers, multiply all the numbers and return the value in the end.
Solution:
def multiply(d):
total = 1
for key in d:
total = total * d[key]
return total
print(multiply({'l': 4, 'o': 11, ' ': 2, 'w': 1, 'r': 1, 'd': 1}))
[14.15] Given a list of words, write a function to find the most frequently occurring word and return its count. Use a dictionary to store the frequenices, then iterate the dictionary to find the maxiumum frequency.
Solution:
def find_most_frequent_word(words):
#Create a dictionary
frequency = {}
#Loop through the list of words to add it to the dictionary
for word in words:
# increment count for that word in the dictionary
if word in frequency:
frequency[word] += 1
#or if word doesn't exist, add to the dictionary
else:
frequency[word] = 1
# keep track of max key and max value
maxVal = 0
maxKey = ""
for key in frequency:
if frequency[key] > maxVal:
maxVal = frequency[key]
maxKey = key
return maxKey
print(find_most_frequent_word(["hello", "me", "hello", "I", "am", "me", "am", "I", "hello", "hello"]))
[14.16] Write a program that takes a dictionary mapping strings to numbers and a limit (a number) and returns True if all the keys are at most the limit in length, and False otherwise.
For example, hasShortKeys({ "abc" : 2, "de" : 5}, 3) would return True, but hasShortKeys({ "abc" : 2, "defgh": 2}, 4) would return False.
Solution:
def hasShortKeys(dictionary, limit):
# Iterate over each key in the dictionary
for key in dictionary:
# Check if the length of the key is greater than the limit
if len(key) > limit:
# If any key's length exceeds the limit, return False
return False
# If all keys' lengths are at most the limit, return True
return True
# Example usage:
dict1 = { "abc" : 2, "de" : 5}
dict2 = { "abc" : 2, "defgh": 2}
print(hasShortKeys(dict1, 3)) # Output: True
print(hasShortKeys(dict2, 4)) # Output: False
[14.17] Write a function called makeAlphabetDict that will create an alphabet ditionary for a list of strings. For each starting letter, create a new list if the letter has not been seen before, or add to the exisiting list if it has been seen.
def makeAlphabetDict(words):
d = { }
for word in words:
letter = word[0]
if letter not in d:
d[letter] = [word]
else:
d[letter].append(word)
return d
print(makeAlphabetDict(["hello", "area", "he", "me", "bye", "my"]))