เรียงข้อมูลใน Python Dictionary ด้วย Value

เคยไหมที่เก็บข้อมูลใน Dictionary ใน python (เก็บเป็น key->value) แล้วต้องการเรียงข้อมูลตาม value

เช่น เก็บคะแนนดังนี้ (key คือ ชื่อคน, value คือ คะแนน)

scores = {'nattster':3.50, 'b4lmung':3.49, 'joe':4.00}

เราสามารถเรียงข้อมูลตาม value ได้อย่างง่ายดายด้วยคำสั่งต่อไปนี้

sorted_scores = sorted(scores.iteritems(), key=lambda (k,v): (v,k))

แต่! ผลลัพธ์ที่ได้จะเป็น list นะครับ โดยมีสมาชิกเป็น 2-tuple (ผลลัพธ์ที่ได้ตามนี้ครับ)

[('b4lmung', 3.4900000000000002), ('nattster', 3.5), ('joe', 4.0)]

แล้วถ้าต้องการเรียงจากมากไปน้อย ก็เรียกคำสั่ง

sorted_scores.reverse()
Advertisement

ใส่ความเห็น

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  เปลี่ยนแปลง )

Facebook photo

You are commenting using your Facebook account. Log Out /  เปลี่ยนแปลง )

Connecting to %s