Search code examples
pythondictionarycopyextend

How to copy dictionary object value from one key to another?


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


Solution

  • data = input()
    
    dict_ref = {}
    
    
    def is_int(s):
    
    try:
        int(s)
        return True
    except ValueError:
        return False
    
    while data != 'end':
        list_data = data.split('->')
        key = list_data[0].strip()
        values = list_data[1].split(',')
    
        for value in values:
            value = value.strip()
    
            if key not in dict_ref.keys() and is_int(value):
                dict_ref[key] = [value]
    
            elif key in dict_ref.keys() and is_int(value):
                dict_ref[key].append(value)
    
            else:
            '''
            With Python dictionaries, when you assign a key to the value of another, the refresh is done automatically.
            For example, writing in this condition, dict_ref [key] = dict_ref [value], when the while loop will start with a new data value, 
            dict_ref [key] = dict_ref [value] will be dynamically updated with the new data as well.
            That's why you should not make a direct assignment, you have to create a new variable that will contain Peter's values,
            then you will assign to the key 'Isacc'.
            '''
                vals = list() #New List
                for val in dict_ref[value]:
                    vals.append(val)
                dict_ref[key] = vals
    
        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

    Output:

    Peter === 1, 2, 3, 4, 5

    Isacc === 1, 2, 3