การลบค่าที่ซ้ำกันในพจนานุกรม Python? [ซ้ำ]
Oct 21 2020
มีคำถามเกี่ยวกับแนวคิดมากกว่าการเข้ารหัสโดยตรง แต่สมมติว่าฉันมีพจนานุกรมคล้ายกับอันนี้
Dict = {'A':1, 'B':3, 'C':3, 'D':4, 'E':1}
Dict2 = {}
และฉันต้องการใช้อินสแตนซ์ทั้งหมดคือคีย์สองอันมีค่าเท่ากันและใส่ไว้ในพจนานุกรมอื่นกระบวนการประเภทใดที่มีประสิทธิภาพมากที่สุด ฉันได้ลองใช้มาตรการเช่น
for value in Dict.items()
for a in value:
if a != b:
continue
else:
Dict2.append(a)
continue
แต่ไม่มีโชค
คำตอบ
1 Jackson Oct 21 2020 at 12:09
คุณสามารถทำสิ่งนี้:
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)
ต้นฉบับ:
{'A': 1, 'B': 3, 'C': 3, 'D': 4, 'E': 1}
ผลลัพธ์:
{1: {'A', 'E'}, 3: {'B', 'C'}, 4: {'D'}}
Steve Oct 21 2020 at 12:14
โรงเรียนเก่ากับลูปปกติ อาจทำได้โดยใช้ list หรือการเขียนตามความเข้าใจ แต่ทำได้ง่ายและชัดเจน:
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)
ผลลัพธ์:
{'D': 4}
{'A': 1, 'E': 1, 'B': 3, 'C': 3}