簡體   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

首先,我很抱歉標題令人困惑,但讓我們假設我們有一本字典:

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

我如何到達這個 output?

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

感謝您的時間!

這個解決方案對我來說似乎很 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()
}

請注意:不要給您的字典dict名稱,因為這是一個關鍵字,這樣您可能會遇到麻煩。

此解決方案也適用於您的情況。

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