Exercise Solutions: Dictionaries¶
Part A: Search a Dictionary¶
Write a function called
return_cost
that takes a dictionary and flavor choice as parameters.The function searches the dictionary for the flavor and returns its cost.
If the flavor is not in the dictionary, return a value of
0
.
1 2 3 4
def return_cost(menu, item): if item in menu: return menu[item] return 0
Write a function called
fanciest_flavor
that takes a dictionary as a parameter. The function should return the key name for the most expensive choice in the dictionary.1 2 3 4 5 6 7 8
def fanciest_flavor(menu): highest_cost = 0 fanciest = '' for (flavor, price) in menu.items(): if price > highest_cost: fanciest = flavor highest_cost = price return fanciest
Part B: Keys from a Collection¶
Write a function called
assign_tickets
that takes a list of names as a parameter.1
def assign_tickets(names):
For the value of each key, assign a random integer from 100-500.
tickets[name] = random.randint(100, 500)
In
main()
, call theassign_tickets
function and assign the result to aticket_holders
variable.ticket_holders = assign_tickets(names)
Part C: Modify Values¶
Call the function fix_tickets
, and use ticket_holders
as the argument.
The fix_tickets
function should:
Accept a dictionary as a parameter.
Loop through the dictionary and check each ticket number to see if it is in the range 100-199 (including the end points).
For a ticket within the range, increase its value by
500
and reassign it to the key.Unless you cloned the dictionary, there is no need to return the updated collection.
1 2 3 4 | def fix_tickets(tickets):
for (key, value) in tickets.items():
if 100 <= value <= 199:
tickets[key] += 500
|
Part D: Counting Characters¶
Write a function called character_count
that counts how many times each
character appears in a string.
The function should:
Accept a string as a parameter.
Create an empty dictionary called
counts
.Loop through the string and check each character.
If the character does NOT exist in as a key in
counts
, add it and assign it a value of1
.If the character DOES exist as a key in
counts
, increase its value by one.
Return the completed
counts
dictionary and assign it to aresults
variable inmain()
.
1 2 3 4 5 6 7 8 | def character_count(a_string):
counts = {}
for char in a_string.lower():
if char in counts:
counts[char] += 1
else:
counts[char] = 1
return counts
|
Part E: Use a List to Sort Key/Value Output¶
In the
main()
function, loop through theresults
dictionary and print each key/value pair on its own line.1 2
for (key, value) in results.items(): print(f"{key}: {value}")
Modify your code again, but this time display the character counts in alphabetical order.
Use the
list
function to create a list of the keys from theresults
dictionary.Sort the list, then use a loop to print the key/value pairs, one pair per line.
1 2
keys = list(results.keys()) keys.sort()