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

Cách tạo dictionary từ tuple cho trước trong Python?

Có thể dùng hàm zip() tạo iterable từ hai tuple (mỗi tuple tương ứng key và value), sau đó dùng dict() tạo dictionary.

>>> T1 = ('a','b','c','d')
>>> T2 = (1,2,3,4)
>>> dict((x,y) for x,y in zip(T1, T2))
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Cú pháp dictionary comprehension cũng có thể dùng:

>>> d = {k:v for (k,v) in zip(T1, T2)}
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}