[英]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.