如何将字典对象的值从一个键复制到另一个?

时间:2019-08-30 11:57:03

标签: python dictionary copy extend

我必须用输入制作字典,其中可能包含“键-> value1,value2”或“键->键”。 键始终是字符串,值始终是整数,由逗号和空格分隔。 如果给定键和值,则必须将值存储到给定键。 如果键已经存在,则必须将给定值添加到旧值中。 如果提供了一个键和另一个键,则必须将另一个键的值复制到第一个键。 如果另一个键不存在,则必须忽略此输入行。 当我收到命令“ end”时,必须停止读取输入行,并且必须以以下格式打印所有键及其值: {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]))

输入:

Peter-> 1,2,3

Isacc->彼得

Peter-> 4,5

结束

预期输出:

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

Isacc === 1,2,3

实际输出:

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

Isacc === 1,2,3,4,5

1 个答案:

答案 0 :(得分:0)

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]))

输入:

Peter-> 1,2,3

Isacc->彼得

Peter-> 4,5

结束

输出:

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

Isacc === 1,2,3