如果值与给定字典中的一个键相等,如何将第一个键的值附加到所述值的键上

2024-06-01 05:15:53 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我很抱歉让人困惑的标题,但让我们假设我们有一本字典:

dict = {'Parent': 'Grandparent', 'Daughter': 'Parent', 'Son': 'Parent'}

如何达到这个输出

new_dict = {'Parent': 'Grandparent', 'Daughter': ['Parent', 'Grandparent'], 'Son': ['Parent', 'Grandparent']}

我在想:

for key in dict:
     for value in dict.values():
       if key == value: #I didn't use 'in' because the string 'Parent' is part of 'Grandparent
         #some action

谢谢你的时间


Tags: keyin标题newforif字典value
2条回答

此解决方案也适用于您的情况

sample_dict = {'Parent': 'Grandparent', 'Daughter': 'Parent', 'Son': 'Parent'}

for key,value in sample_dict.items():
    if value in sample_dict:
        sample_dict[key]=[value,sample_dict[value]]

print(sample_dict)
{'Parent': 'Grandparent', 'Daughter': ['Parent', 'Grandparent'], 'Son': ['Parent','Grandparent']}

在我看来,这个解决方案很有吸引力:

dict_ = {'Parent': 'Grandparent', 'Daughter': 'Parent', 'Son': 'Parent'}

new_dict = {
    k: list(set(v for v in dict_.values()
    if v != k)) for k,v in dict_.items()
}

请注意:不要给你的字典dict起名字,因为这是一个关键字,所以你可能会遇到麻烦

相关问题 更多 >