names_ages = {"Paul": 32, "Patricia": 44, "Eduardo": 27}
for key in names_ages:
names_ages[key] += 1
names_ages
{'Paul': 33, 'Patricia': 45, 'Eduardo': 28}
You can change dictionary values using keys
sales_tax
def sales_tax(dictionary):
for key in dictionary:
dictionary[key] = round(dictionary[key] * 0.056, 2)
return dictionary
def main():
groceries = {"banana": 2.50, "milk": 4.25, "bread": 3.68}
sales_tax(groceries)
assert groceries == {'banana': 0.14, 'milk': 0.24, 'bread': 0.21}
print(groceries)
main()
{'banana': 0.14, 'milk': 0.24, 'bread': 0.21}
sales_tax
def sales_tax(dictionary):
result = {}
for key, value in dictionary.items():
result[key] = round(value * 0.056, 2)
return result
def main():
groceries = {"banana": 2.50, "milk": 4.25, "bread": 3.68}
assert sales_tax(groceries) == {'banana': 0.14, 'milk': 0.24, 'bread': 0.21}
print( sales_tax(groceries) )
main()
{'banana': 0.14, 'milk': 0.24, 'bread': 0.21}
key: value
from a dictionaryCannot iterate over a dictionary and change its size:
RuntimeError: dictionary changed size during iteration
key: value
from a dictionaryUse another data structure (like a set) instead
remove_records
def remove_records(dictionary):
for k in set(dictionary):
if len(k) > 0 and k[0].lower() == k[-1].lower():
dictionary.pop(k)
return dictionary
def main():
students = {"Anna": "A", "Peter": "B", "Bob": "D", "Cedric": "A"}
remove_records(students)
assert students == {"Peter": "B"}
print(students)
main()
{'Peter': 'B'}
repetition
def repetition(dictionary):
for key, value in dictionary.items():
dictionary[key] = [key] * value
return dictionary
def main():
test_dictionary = {"a": 5, "b": 2, "c": 3}
repetition(test_dictionary)
assert test_dictionary == {"a": ["a", "a", "a", "a", "a"],
"b": ["b", "b"], "c": ["c", "c", "c"] }
print(test_dictionary) # {"a": ["a", "a", "a", "a", "a"],
# "b": ["b", "b"], "c": ["c", "c", "c"] }
main()
{'a': ['a', 'a', 'a', 'a', 'a'], 'b': ['b', 'b'], 'c': ['c', 'c', 'c']}
get_names
dictionary
that maps one_letter strings to lists of strings, an a string
string
) as a substring (this search is not case sensitive)Test case:
def get_names(dictionary, string):
new_list = []
for name_list in dictionary.values():
for name in name_list:
if string.lower() in name.lower():
new_list.append(name)
return new_list
def main():
names = { "R": ["Randy", "Roger"],
"S": ["Steve", "Sally"],
"T": ["Tanner"] }
print( get_names(names, "er") ) # ["Roger", "Tanner"]
main()
['Roger', 'Tanner']