เมื่อต้องการรวมค่าทั้งหมดจากทุกลิสต์ในดิกชันนารี และลบค่าซ้ำ แล้วเรียงลำดับ ใช้ Set Comprehension ร่วมกับ sorted()
ตัวอย่างโค้ด
my_dict = {
'hi': [5, 3, 8, 0],
'there': [22, 51, 63, 77],
'how': [7, 0, 22],
'are': [12, 11, 45],
'you': [56, 31, 89, 90]
}
print("The dictionary is:")
print(my_dict)
unique_vals = sorted({elem for val_list in my_dict.values() for elem in val_list})
print("The unique values are:")
print(unique_vals)ผลลัพธ์
The dictionary is: {'hi': [5, 3, 8, 0], 'there': [22, 51, 63, 77], 'how': [7, 0, 22], 'are': [12, 11, 45], 'you': [56, 31, 89, 90]}
The unique values are: [0, 3, 5, 7, 8, 11, 12, 22, 31, 45, 51, 56, 63, 77, 89, 90]คำอธิบาย
my_dict.values()ได้ลิสต์ของลิสต์ค่าSet Comprehension
{elem for val_list in ... for elem in val_list}แบนและลบซ้ำพร้อมกันsorted()เรียงค่าจากน้อยไปมากผลลัพธ์เป็นลิสต์ตัวเลขไม่ซ้ำเรียงลำดับ