简体   繁体   English

如果 value 与给定字典中的 key 相等,我怎么能 append 到 key 的 value 的第一个 key

[英]If value is equal with a key in the given dictionary, how can I append to the key of the said value the value of the first key

First of all, I am sorry for the confusing title but let's assume we have a dictionary:首先,我很抱歉标题令人困惑,但让我们假设我们有一本字典:

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

How do I reach this output?我如何到达这个 output?

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

I was thinking of this:我在想这个:

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

Thank you for your time!感谢您的时间!

This solution seems quite Pythonic to me:这个解决方案对我来说似乎很 Pythonic:

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()
}

Please, note: do not give your dictionary dict name as this is a keyword so you can get into troubles.请注意:不要给您的字典dict名称,因为这是一个关键字,这样您可能会遇到麻烦。

This solution also works for your case.此解决方案也适用于您的情况。

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']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM