Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Lấy khóa từ điển dưới dạng danh sách trong Python

Các phương pháp trích xuất khóa của từ điển thành danh sách.

Cách 1: Dùng dict.keys()

Adict = {1:'Sun',2:'Mon',3:'Tue',4:'Wed'}
print("The given dictionary is :\n ", Adict)
print(list(Adict.keys()))

Kết quả: [1, 2, 3, 4]

Cách 2: Dùng toán tử * (unpacking)

Adict = {1:'Sun',2:'Mon',3:'Tue',4:'Wed'}
print("The given dictionary is :\n ", Adict)
print([*Adict])

Kết quả: [1, 2, 3, 4]

Cách 3: Dùng itemgetter

from operator import itemgetter
Adict = {1:'Sun',2:'Mon',3:'Tue',4:'Wed'}
print("The given dictionary is :\n ", Adict)
print(list(map(itemgetter(0), Adict.items())))

Kết quả: [1, 2, 3, 4]