我正在嘗試對以下字典進行排序:
test_dict = {
'a': [1,3,5],
'b': [9,3,4],
'c': [4,5,6],
'd': [1,3,6],
'e': [1,3,5],
'f': [1,3,5],
'g': [4,5,6],
'h': [6,5,9]
}
我必須將元組中所有具有重復值的鍵作為字典鍵與它們具有的一個值結合起來。
結果,我想得到類似的東西:
result = {
('a','e','f'): [1,3,5],
'b': [9,3,4],
('c','g'): [4,5,6],
'd': [1,3,6],
'h': [6,5,9]
}
我已經嘗試了很多東西,但我只實作了按值搜索:
test_dict = {
'a': [1,3,5],
'b': [9,3,4],
'c': [4,5,6],
'd': [1,3,6],
'e': [1,3,5],
'f': [1,3,5],
'g': [4,5,7],
'h': [6,5,9]
}
list_to_find = [1,3,5]
def found_duplicates(target_dict, value_to_find):
found_keys = []
for k in test_dict.keys():
value_for_k = test_dict[k]
if(value_for_k == list_to_find):
found_keys.append(k)
return tuple(found_keys)
print(found_duplicates(test_dict, list_to_find))
找到所有重復值、將該值的鍵組合在一個元組中并回傳新字典的更好方法是什么?
uj5u.com熱心網友回復:
嘗試:
out = {}
for k, v in test_dict.items():
out.setdefault(tuple(v), []).append(k)
out = {v[0] if len(v) == 1 else tuple(v): list(k) for k, v in out.items()}
print(out)
印刷:
{
("a", "e", "f"): [1, 3, 5],
"b": [9, 3, 4],
("c", "g"): [4, 5, 6],
"d": [1, 3, 6],
"h": [6, 5, 9],
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/525473.html
標籤:Python排序字典
