Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

แปลงพจนานุกรมเป็นลิสต์ของ tuples ใน Python

แปลง key-value pairs ใน dictionary ให้เป็นลิสต์ของ tuples

ใช้ dict.items() ใน list comprehension

[(key, val) for key, val in Adict.items()]

ตัวอย่าง

Adict = {30: 'Mon', 11: 'Tue', 19: 'Fri'}
print("The given dictionary: ", Adict)
Alist = [(key, val) for key, val in Adict.items()]
print("The list of tuples: ", Alist)

ผลลัพธ์

The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]

ใช้ zip

list(zip(Adict.keys(), Adict.values()))

ตัวอย่าง

Adict = {30: 'Mon', 11: 'Tue', 19: 'Fri'}
print("The given dictionary: ", Adict)
Alist = list(zip(Adict.keys(), Adict.values()))
print("The list of tuples: ", Alist)

ผลลัพธ์

The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]

ใช้ append ใน for loop

วนลูป key สร้าง tuple append เข้า list

ตัวอย่าง

Adict = {30: 'Mon', 11: 'Tue', 19: 'Fri'}
print("The given dictionary: ", Adict)
Alist = []
for x in Adict:
    k = (x, Adict[x])
    Alist.append(k)
print("The list of tuples: ", Alist)

ผลลัพธ์

The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]