Doppelte Werte in Python-Wörterbüchern entfernen? [Duplikat]
Oct 21 2020
Eher eine Konzeptfrage als eine direkt codierende. Aber sagen wir, ich hätte ein Wörterbuch, das diesem ähnlich ist.
Dict = {'A':1, 'B':3, 'C':3, 'D':4, 'E':1}
Dict2 = {}
Und ich wollte alle Instanzen nehmen, in denen zwei Schlüssel den gleichen Wert hatten, und sie in ein anderes Wörterbuch einfügen. Welche Art von Prozess ist am effizientesten? Ich habe Maßnahmen wie versucht
for value in Dict.items()
for a in value:
if a != b:
continue
else:
Dict2.append(a)
continue
Aber zu keinem Glück.
Antworten
1 Jackson Oct 21 2020 at 12:09
Sie können so etwas tun:
Dict = {'A':1, 'B':3, 'C':3, 'D':4, 'E':1}
result = {}
for k, v in Dict.items():
result.setdefault(v, set()).add(k)
print("Original: ")
print(Dict)
print("------------")
print("Result: ")
print(result)
Original:
{'A': 1, 'B': 3, 'C': 3, 'D': 4, 'E': 1}
Ergebnis:
{1: {'A', 'E'}, 3: {'B', 'C'}, 4: {'D'}}
Steve Oct 21 2020 at 12:14
Alte Schule mit regelmäßigen Schleifen. Könnte vielleicht mit Listen- oder Diktatverständnissen gemacht werden, aber das ist einfach und offensichtlich:
dict = {'A':1, 'B':3, 'C':3, 'D':4, 'E':1}
# Make a reverse dictionary that maps values to lists of keys
# that have that value in the original dict
reverse_dict = {}
for k, v in dict.items():
reverse_dict.setdefault(v, list()).append(k)
# Show the reverse dict
# print(reverse_dict)
# Move entries for keys that had duplicates from the original
# dict to a new dict
dups_dict = {}
for k, vs in reverse_dict.items():
if len(vs) > 1: # if there was more than one key with this value
for v in vs: # for each of those keys
dups_dict[v] = k # copy it to the new dict
del dict[v] # and remove it from the original dict
# Show the original dict and the new one
print(dict)
print(dups_dict)
Ergebnis:
{'D': 4}
{'A': 1, 'E': 1, 'B': 3, 'C': 3}