In: Computer Science
Write a function that accepts a dictionary and produces a sorted list of tuples
The dictionary looks like this:
{‘US’: [{'Chicago, IL': ('2/1/2020 19:43', 2, 0, 0)}, {'San Benito, CA': ('2/3/2020 3:53', 2, 0, 0)}, {'Santa Clara, CA': ('2/3/2020 0:43', 2, 0, 0)}, {'Boston, MA': ('2/1/2020 19:43', 1, 0, 0)}, {'Los Angeles, CA': ('2/1/2020 19:53', 1, 0, 0)}, {'Orange, CA': ('2/1/2020 19:53', 1, 0, 0)}, {'Seattle, WA': ('2/1/2020 19:43', 1, 0, 0)}, {'Tempe, AZ': ('2/1/2020 19:43', 1, 0, 0)}], 'Australia' : [{'New South Wales': ('2/1/2020 18:12', 4, 0, 2)}, {'Victoria': ('2/1/2020 18:12', 4, 0, 0)}, {'Queensland': ('2/4/2020 16:53', 3, 0, 0)}, {'South Australia': ('2/2/2020 22:33', 2, 0, 0)}]
For these counts, I need to use the numbers that are bolded above). The returned sorted list (in descending order) will contain key-value pairs such that each key is a country and the corresponding value is the number of cases observed within that country.
For example: [('Australia', 13),(‘US’: 11)]
All the explanation is in the code comments. Hope this helps!
Code:
# required function
def func(dictionary):
# initial dictionary
res = {}
# loop for all keys in dictionary
for key in dictionary.keys():
# store the sum of cases
sum_cases = 0
# loop for all elements in list for key
for e in dictionary[key]:
# get the key and the tuple associated
for k in e.keys():
# get the second value (index = 1) of tuple
sum_cases = sum_cases + e[k][1]
# add the key and sum to dictionary
res[key] = sum_cases
# now sort the res to form a list of tuple
res = sorted(res.items(), key=lambda item: item[1],
reverse=True)
# return result
return res
# sample run
x = {'US': [{'Chicago, IL': ('2/1/2020 19:43', 2, 0, 0)},
{'San Benito, CA': ('2/3/2020 3:53', 2, 0, 0)},
{'Santa Clara, CA': ('2/3/2020 0:43', 2, 0, 0)},
{'Boston, MA': ('2/1/2020 19:43', 1, 0, 0)},
{'Los Angeles, CA': ('2/1/2020 19:53', 1, 0, 0)},
{'Orange, CA': ('2/1/2020 19:53', 1, 0, 0)},
{'Seattle, WA': ('2/1/2020 19:43', 1, 0, 0)},
{'Tempe, AZ': ('2/1/2020 19:43', 1, 0, 0)}],
'Australia' : [{'New South Wales': ('2/1/2020 18:12', 4, 0,
2)},
{'Victoria': ('2/1/2020 18:12', 4, 0, 0)},
{'Queensland': ('2/4/2020 16:53', 3, 0, 0)},
{'South Australia': ('2/2/2020 22:33', 2, 0, 0)}]}
# call the function
print('Result:',func(x))
Sample run:
Code screenshots: