In: Computer Science
Write a Python function that returns a list of keys in aDict with the value target. The list of keys you return should be sorted in increasing order. The keys and values in aDict are both integers. (If aDict does not contain the value target, you should return an empty list.)
This function takes in a dictionary and an integer and returns a list.
def keysWithValue(aDict, target):
'''
aDict: a dictionary target: an integer
'''
# Your code here
Solution:
The program is written in python 3.
Code of function:
def keysWithValue(aDict, target):
'''
aDict: a dictionary target: an integer
'''
# Initialize matchList
result = []
# Find all values in aDict that match, put their keys in result
for key in aDict:
if aDict[key] == target:
result.append(key)
# Sort result and return
result.sort()
return result
Complete code with test case:
def keysWithValue(aDict, target):
'''
aDict: a dictionary target: an integer
'''
# Initialize matchList
result = []
# Find all values in aDict that match, put their keys in result
for key in aDict:
if aDict[key] == target:
result.append(key)
# Sort result and return
result.sort()
return result
#For Testing
aDict = {1 : 11, 2 : 22, 3 : 33, 5 : 44, 4 : 44}
print(keysWithValue(aDict, 11))
print(keysWithValue(aDict, 44))
print(keysWithValue(aDict, 77))
Screenshot of code and output :