[英]Python Dictionary: how to remove multiple keys for the same values
這是編寫此代碼的正確方法
getter = {
0 : "value_1",
1 : "value_1",
2 : "value_1",
3 : "value_2",
4: "value_3"
}
並將值作為
for k in keys:
value = getter[ keys ]
#.. then, you do other stuffs with the picked value
我想避免在字典聲明中為不同的鍵重復“value_1”行。
getter = {
0 : "value_1",
1 : "value_1",
2 : "value_1",
3 : "value_2",
4: "value_3"
}
temp={val:key for key,val in getter.items()}
res={val:key for key, val in temp.items()} # {2: 'value_1', 3: 'value_2', 4: 'value_3'}
您可以像這樣從字典中刪除重復項。
但是,如果您不必跳過getter
的任何鍵,則可以在執行某些操作后保存並檢查該鍵。
processed_value = list()
for key, value in getter.items():
if value in processed_value:
continue
processed_value.append(value)
#.. then, you do other stuffs with the picked value
如果您想要特定的鍵,那么您可能必須遍歷字典並使用您要查找的值保存您想要的鍵,如果您不關心您想要的鍵,那么@Lazyer 答案會幫助您
只是為了好玩,在一個單一的聲明中......使用這個事實
reversed
)getter_new = dict(zip(*reversed(list(zip(*dict(zip(*reversed(list(zip(*getter.items()))))).items())))))
print(getter_new)
#{2: 'value_1', 3: 'value_2', 4: 'value_3'}
請注意,具有重復值的最后一個鍵將是“主導”鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.