A dictionary or dict
in Python is a object that can store a mapping from "keys" to "values".
We can define a dictionary like this:
countryCapitals = {
'Ethiopia': 'Addis Abada',
'Canada': 'Ottawa',
'Iran': 'Teheran',
'Turkey': 'Ankara'
}
This dictionary maps the names of each country (the key) to the name of its capital (the value). Once the dictionary is defined, we can get a value corresponding to a given key using square bracket notation:
countryCapitals['Ethiopia']
'Addis Abada'
We can also replace entries or add new ones:
countryCapitals['Ethiopia'] = 'Addis Ababa'
countryCapitals['Ethiopia']
'Addis Ababa'
countryCapitals['Taiwan'] = 'Taipei'
countryCapitals['Taiwan']
'Taipei'
There are also a few useful methods (functions defined on objects) that give you the full list of keys, or the full list of values, or the number of entries.
countryCapitals.keys()
dict_keys(['Ethiopia', 'Canada', 'Iran', 'Turkey', 'Taiwan'])
countryCapitals.values()
dict_values(['Addis Ababa', 'Ottawa', 'Teheran', 'Ankara', 'Taipei'])
len(countryCapitals)
5
You can also check if a key exists in the dictionary using the in
operator.
'Iran' in countryCapitals
True
'Iraq' in countryCapitals
False
We have a dictionary that links a username to the user's full name:
users = {
'koomaster': 'Stephen Koo',
'hawidoin': 'Hawi Abraham',
'unicornprincess': 'Winston Du',
'kiyam': 'Kidist Amdie',
}
What will users.keys()
output?
What will users.values()
output?
What will len(users)
output?
What will 'hawidoin' in users
output?
What will 'puppykiller' in users
output?
Raise your hand before moving on to ask a TA to check your answers if you'd like.
Write a dictionary friendsAge
mapping the names of five of your friends to their ages. In other words, we want a dictionary with students names as keys and ages as values.
Write a function averageFriendsAge(d)
where d
is a dictionary mapping the names of friends to their ages and that returns the average age of all the friends in the dictionary d
.
def averageFriendsAge(d):
# Fill in your code here.
# Test your code here.
friendsAge = {"Barney": 500, "Cailou": 4,
"Lala": 2, "Blue": 19, "Jimmy Newtron": 14}
print(averageFriendsAge(friendsAge)) # Should be 107.8
Now, write a function addFriend(d, name, age)
where d
is a dictionary mapping the names of friends to their ages, name
is a string and age
is an integer, that returns an updated dictionary containing the new entry.
Use it to add Selam, your 3.3 million-year-old friend, to your friendsAge
dictionary.
def addFriend(d, name, age):
# Fill in your code here.
print(addFriend(friendsAge, 'Selam', 3300000))
Selam drinks a magic potion and gets 1.3 million years younger. Write a function modifyAge(d, name, age)
to update one of your friends age, where d
is a dictionary mapping the names of friends to their ages, name
is a string and age
is an integer, that returns the updated dictionary.
def modifyAge(d, name, age):
# Fill in your code here.
print(modifyAge(friendsAge, 'Selam', 2000000))
Compare addFriend(d, name, age)
and modifyAge(d, name,age)
functions. What does it tell you about the dictionaries property?
Write a function getFriendAge(d, name)
where d
is a dictionary mapping the names of friends to their ages and name
is a string, that returns the age of your friend.
What happens if you run it with a name not in your dictionary? In this case return -1
.
def getFriendAge(d, name):
# Fill in your code here.
getFriendAge(friendsAge, 'Selam')
In Lecture 2 Exercices (Part 2), we wrote a function mostCommon(s)
that takes in a string s
and returns the most common character in a string. If no character occurs more often than other character, return any character in the string.
For example, mostCommon('salaam') = 'a'
Also, mostCommon('abc') = 'a', 'b' or 'c'
Now, we want to rewrite this function using a dictionary without changing the argument of the function.
def mostCommon(s):
# Fill in your code here.
# Test your code here.
mostCommon('aaadjfkdjkfjdjfaaaaaaa')
In Lecture 5 Exercises (Part 1), we wrote a function numTimes(s, letter)
that returned how many times letter
appears in s
.
For example numTimes("scccscccccc", "s") = 2.
Another example: numTimes("cccc", "s") = 0.
Also: = 0.
Now, we want to rewrite this function using a dictionary.
def numTimes(s, letter):
# Fill in your code here.
# Test your code here.
print(numTimes("scccscccccc", "s"))
print(numTimes("cccc", "s"))
print(numTimes("", "s"))
Similarly, we want to write a function encodeString(s)
that takes in a string s and returns a string of the encoded letters.
For example, encodeString('aabbb')
returns 'a2b3'
Also, encodeString('abbbaac')
returns 'a3b3c1'
Also, encodeString('')
returns ''
def encodeString(s):
# Fill in your code here.
# Test your code here
print(encodeString(''))
print(encodeString('abccddb'))
We are given two lists: one list (lNames
) of students names as strings and one list (lGrades
) of grades from A to F as strings. We want to write a function mergeListAsDict(lNames, lGrades)
that takes the two lists as inputs and returns a dictionary with the names of the sudents as key and the grade as value.
For example, mergeListsAsDict(['Daniel', 'Rupal'], ['F', 'A'])
returns {'Daniel': 'F', 'Rupal': 'A'}
def mergeListsAsDict(lNames, lGrades):
# Complete the function here
lNames = ['Daniel', 'Basi', 'Rupal', 'Dim', 'Leello', 'Mike']
lGrades = ['F', 'B', 'A', 'C', 'A', 'B']
mergeListsAsDict(lNames, lGrades)
Run the cell below to verify your solution
dictResult = {
'Daniel': 'F',
'Basi': 'B',
'Rupal': 'A',
'Dim': 'C',
'Leello': 'A',
'Mike': 'B'
}
assert mergeListsAsDict(
lNames, lGrades) == dictResult, 'The solution is incorrect'
Write a function getStudentsWithGrade(d, grade)
where d
is the dictionary mapping sutdents names to grades and grade
is a grade (from A to F) as a string, that returns a list of students with that given grade.
For example, getStudentsWithGrade({'Daniel': 'F', 'Rupal': 'A'}, 'A')
returns ['Rupal']
.
Also, getStudentsWithGrade({'Daniel': 'A', 'Rupal': 'A'}, 'A')
returns ['Daniel', 'Rupal']
.
Also, getStudentsWithGrade({'Daniel': 'F', 'Rupal': 'A'}, 'D')
returns []
def getStudentWithGrade(d, grade):
# Fill in your code here.
mergeDict = {
'Daniel': 'F',
'Basi': 'B',
'Rupal': 'A',
'Dim': 'C',
'Leello': 'A',
'Mike': 'B'}
getStudentWithGrade(mergeDict, 'F')
We are given a dictionary friends
mapping people to their friends. We want to write a function getFriendsOfFriends(d)
where d
would be that dictionary mapping people to their friends, that returns anonther dictionary mapping the same keys of people to friends of their friends. We can assume each person can't be friends with themselves.
For example,
getFriendsOfFriends({'Amy': ['Daniel', 'Basi', 'Teddy'],
'Teddy': ['Rupal', 'Elvis', 'Amy']})
returns {'Amy': ['Rupal', 'Elvis'], 'Teddy': ['Daniel', 'Basi']}
def getFriendsOfFriends(friends):
# Fill in your code here.
friends = {
'Basi': ['Leello', 'Jessica', 'Corina', 'Isabelle'],
'Jessica': ['Rupal', 'Daniel', 'Dim'],
'Arash': ['Will', 'Mike'],
'Mike': ['Will', 'Jessica', 'Arash'],
'Corina': ['Basi', 'Leello'],
'Isabelle': ['Arash', 'Rupal', 'Mike'],
'Daniel': [] # :(
}
getFriendsOfFriends(friends)
friendsOfFriends = {
'Basi': ['Rupal', 'Daniel', 'Dim', 'Leello', 'Arash', 'Mike'],
'Jessica': [],
'Arash': ['Will', 'Jessica'],
'Mike': ['Rupal', 'Daniel', 'Dim', 'Will'],
'Corina': ['Leello', 'Jessica', 'Isabelle'],
'Isabelle': ['Will', 'Mike', 'Jessica', 'Arash'],
'Daniel': []
}
assert getFriendsOfFriends(
friends) == friendsOfFriends, 'The solution is incorrect'
There has been a case of food poisoning at the cafeteria Monday. We want to write a function getDistinctEntriesCount(d)
that takes d
, which is a dictionary mapping the days of the week to a list of entries in the cafeteria. The function should return another dictionary mapping the day to the number of distinct people who ate at the cafeteria each day.
For example, getDistinctEntriesCount({'Segno': ['rupal', 'rupal']})
returns {'Segno': 1}
Also, getDistinctEntriesCount({'Segno': ['rupal', 'rupal'], 'Arb': ['isa']})
returns {'Segno': 1, 'Arb': 1}
def getDistinctEntriesCount(entries):
# Complete the function here
entries = {
'Segno': ['arash', 'arash', 'isa', 'rupal', 'arash', 'leello'],
'Maksegno': ['leello', 'dim', 'arash', 'arash', 'isa', 'rupal', 'nati', 'arash', 'nati', 'basi'],
'Erob': ['leello', 'dim', 'dim', 'dim', 'arash'],
'Hamus': ['arash', 'arash', 'rupal', 'arash'],
'Arb': ['leello', 'leello', 'isa', 'dim', 'rupal', 'corina', 'basi', 'nati']
}
getDistinctEntriesCount(entries)
distinctEntries = {
'Segno': 4,
'Maksegno': 7,
'Erob': 3,
'Hamus': 2,
'Arb': 7
}
assert distinctEntries == getDistinctEntriesCount(
entries), 'The solution is incorrect'