【问题标题】:How to copy dictionary object value from one key to another?如何将字典对象值从一个键复制到另一个键?
【发布时间】:2020-01-03 16:22:08
【问题描述】:

我必须制作一个带有输入的字典,其中可能包含“key -> value1, value2”或“key -> key”。 键总是字符串,值总是整数,用逗号和空格分隔。 如果给定一个键和值,我必须将值存储到给定的键中。 如果密钥已经存在,我必须将给定的值添加到旧的值中。 如果给定一个键和另一个键,我必须将另一个键的值复制到第一个键。 如果其他键不存在,则必须忽略此输入行。 当我收到“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]))

输入:

彼得 -> 1, 2, 3

艾萨克 -> 彼得

彼得 -> 4, 5

结束

预期输出:

彼得 === 1、2、3、4、5

Isacc === 1、2、3

实际输出:

彼得 === 1、2、3、4、5

Isacc === 1、2、3、4、5

【问题讨论】:

  • “预期输出” 用什么输入?在您的示例输入中,我既看不到 Peter 也看不到 Isaac。
  • 对不起,我加了。

标签: python dictionary copy extend


【解决方案1】:
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]))

输入:

彼得 -> 1, 2, 3

艾萨克 -> 彼得

彼得 -> 4, 5

结束

输出:

彼得 === 1、2、3、4、5

Isacc === 1、2、3

【讨论】:

  • 非常感谢@Sekouba,这解决了我的问题。我只需要检查 dict.ref.keys() 中是否存在“值”(如果它是字符串),如果不存在则通过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2019-06-19
  • 2021-03-04
  • 1970-01-01
  • 2011-02-07
  • 2020-09-26
相关资源
最近更新 更多