I have to make a dictionary with input, which may contain "key -> value1, value2" or "key -> key". The keys are always strings, and the values are always integers, separated by a comma and a space. If given a key and values, I must store the values to the given key. If the key already exists, I must add the given values to the old ones. If given a key and another key, I must copy the values of the other key to the first one. If the other key does not exist, this input line must be ignored. When I receive the command “end”, I must stop reading input lines, and must print all keys with their values, in the following format: {key} === {value1, value2, value3}
data = input()
dict_ref = {}
def is_int(s):
try:
int(s)
return True
except ValueError:
return False
while data != "end":
list_data = data.split(" -> ")
name = list_data[0]
values = list_data[1].split(", ")
if name not in dict_ref and is_int(values[0]):
dict_ref[name] = values
elif values[0] in dict_ref:
dict_ref[name] = dict_ref[values[0]]
elif name in dict_ref and is_int(values[0]):
dict_ref[name].extend(values)
data = input()
for item in dict_ref:
print(f"{item} === ", end="")
print(", ".join(dict_ref[item]))
Input:
Peter -> 1, 2, 3
Isacc -> Peter
Peter -> 4, 5
end
Expected output:
Peter === 1, 2, 3, 4, 5
Isacc === 1, 2, 3
Actual output:
Peter === 1, 2, 3, 4, 5
Isacc === 1, 2, 3, 4, 5