简体   繁体   中英

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?

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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