我想通過洗掉所有具有相同值的鍵來獲得一個新字典(鍵不同,值相同)
例如: 輸入:
dct = {'key1' : [1,2,3], 'key2': [1,2,6], 'key3': [1,2,3]}
預期輸出:
{'key2': [1, 2, 6]}
key1 和 key3 被洗掉,因為它們共享相同的值。
我對此一無所知?
uj5u.com熱心網友回復:
您可以通過基于值創建字典來做到這一點。在這種情況下,值是不可散列的串列,因此轉換為元組。新字典中的值是我們從原始字典中附加任何匹配鍵的串列。最后,通過新字典查找串列長度大于 1 的任何值 - 即,是否重復。然后我們可以從原始字典中洗掉這些鍵。
d = {'key1' : [1,2,3], 'key2': [1,2,6], 'key3': [1,2,3]}
control = {}
for k, v in d.items():
control.setdefault(tuple(v), []).append(k)
for v in control.values():
if len(v) > 1:
for k in v:
del d[k]
print(d)
輸出:
{'key2': [1, 2, 6]}
uj5u.com熱心網友回復:
我創建了一個計數串列,其中包含有關某個專案在字典中出現的次數的資訊。然后我只復制曾經存在的專案。
a = {"key1": [1,2,3], "key2": [1,2,6], "key3": [1,2,3]}
# find how many of each item are there
counts = list(map(lambda x: list(a.values()).count(x), a.values()))
result = {}
#copy only items which are in the list once
for i,item in enumerate(a):
if counts[i] == 1:
result[item] = a[item]
print(result)
uj5u.com熱心網友回復:
正如OP給出的,該問題的最簡單解決方案:
dct = {'key1' : [1,2,3], 'key2': [1,2,6], 'key3': [1,2,3]}
print({k:v for k, v in dct.items() if list(dct.values()).count(v) == 1})
輸出:
{'key2': [1, 2, 6]}
uj5u.com熱心網友回復:
單回圈解決方案:
dict_ = {'key1' : [1,2,3], 'key2': [1,2,6], 'key3': [1,2,3]}
key_lookup = {}
result = {}
for key, value in dict_.items():
v = tuple(value)
if v not in key_lookup:
key_lookup[v] = key
result[key] = value
else:
if key_lookup[v] is not None:
del result[key_lookup[v]]
key_lookup[v] = None
print(result)
輸出:
{'key2': [1, 2, 6]}
uj5u.com熱心網友回復:
dct = {'key1' : [1,2,3], 'key2': [1,2,6], 'key3': [1,2,3]}
temp = list(dct.values())
result = {}
for key, value in dct.items():
for t in temp:
if temp.count(t) > 1:
while temp.count(t) > 0:
temp.remove(t)
else:
if t == value:
result[key] = value
print(result)
輸出:
{'key2': [1, 2, 6]}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/434479.html
