Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Explained solution in Clear category for Convert and Aggregate by Selindian
def conv_aggr(data: list[tuple[str, int]]) -> dict[str, int]:
dict = {} # Define Dictionary
for key, val in data: # Loop over combination of key and value
if not key or not val: continue # Skip this loop if key or val is empty or 0.
if key not in dict.keys(): # If the key is not in the dcitionary ...
dict[key] = val # ... add the key and it's value
else: # if the key is already in the dict ...
dict[key] = dict[key] + val # ... sum old and new value
if dict[key] == 0: # ... if the resulting sum is 0 ...
del dict[key] # ... ... remove the entry from the dict as empty and 0 sums should be excluded.
return dict # return the dictionary
print("Example:")
print(conv_aggr([("a", 7), ("b", 8), ("a", 10)]))
assert conv_aggr([("a", 7), ("b", 8), ("a", 10)]) == {"a": 17, "b": 8}
assert conv_aggr([]) == {}
assert conv_aggr([("a", 5), ("a", -5)]) == {}
assert conv_aggr([("a", 5), ("a", 5), ("a", 0)]) == {"a": 10}
assert conv_aggr([("a", 5), ("", 15)]) == {"a": 5}
print("The mission is done! Click 'Check Solution' to earn rewards!")
Aug. 23, 2022
Comments: