Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second solution - Using setdefault 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 key and val: # ... If key and value not emtpy or 0
newval = dict.setdefault(key, 0) + val # ... ... setdefault allows to add val even if key not in dict yet
if newval: # ... ... if newval is not 0
dict[key] = newval # ... ... ... let val of dict[key] = newval
else: # ... ... otherwise
del dict[key] # ... ... ... remove key as requested
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!")
Sept. 10, 2022
Comments: