Khi cần chuyển tuple thành dictionary với các cặp key-value kề nhau (adjacent pairs), có thể dùng dict(), dictionary comprehension và slicing.
Dictionary lưu trữ cặp (key, value).
Dictionary comprehension là cú pháp ngắn gọn để tạo dict.
Slicing [start:stop] lấy phần tử từ start đến stop-1.
Ví dụ
my_tuple = (7, 8, 3, 4, 3, 2)
print(f"Tuple gốc: {my_tuple}")
# Cách 1: Dictionary comprehension với slicing step=2
# idx: 0, 2, 4 -> cặp (0:2), (2:4), (4:6)
result = {my_tuple[i]: my_tuple[i+1] for i in range(0, len(my_tuple), 2)}
print(f"\nCách 1 - dict comprehension: {result}")
# Cách 2: dict() + generator expression (giống code gốc)
result2 = dict(my_tuple[i:i+2] for i in range(0, len(my_tuple), 2))
print(f"Cách 2 - dict(slicing): {result2}")
# Cách 3: zip + iter trick (Pythonic)
# iter(t) tạo iterator, zip lấy cặp (next, next)
it = iter(my_tuple)
result3 = dict(zip(it, it))
print(f"Cách 3 - zip(iter, iter): {result3}")
Kết quả
Tuple gốc: (7, 8, 3, 4, 3, 2)
Cách 1 - dict comprehension: {7: 8, 3: 2}
Cách 2 - dict(slicing): {7: 8, 3: 2}
Cách 3 - zip(iter, iter): {7: 8, 3: 2}
Giải thích
- Tuple có 6 phần tử:
7, 8, 3, 4, 3, 2. - Cặp kề nhau:
(7,8),(3,4),(3,2). - Key trùng lặp:
3xuất hiện 2 lần -> dict chỉ giữ giá trị cuối (3: 2). - Cách 3
zip(iter, it)là idiom Python kinh điển: iterator chung, mỗinext()lấy 1 phần tử -> tự động ghép cặp.
Xử lý key trùng lặp: Gom giá trị thành list
from collections import defaultdict
def tuple_to_multidict(tup):
"""Chuyển tuple thành dict key->list values, giữ tất cả giá trị."""
result = defaultdict(list)
it = iter(tup)
for k, v in zip(it, it):
result[k].append(v)
return dict(result)
print(tuple_to_multidict(my_tuple))
# {7: [8], 3: [4, 2]}
Tuple lẻ số phần tử (odd length)
odd_tuple = (1, 2, 3, 4, 5)
# Cách 1: Bỏ phần tử cuối
result = dict(zip(iter(odd_tuple), iter(odd_tuple)))
print(result) # {1: 2, 3: 4} - 5 bị bỏ
# Cách 2: Gán giá trị mặc định cho key cuối
from itertools import zip_longest
result2 = dict(zip_longest(odd_tuple[::2], odd_tuple[1::2], fillvalue=None))
print(result2) # {1: 2, 3: 4, 5: None}
Ứng dụng: Parse query string / config
# Query string: key1=val1&key2=val2 -> tuple ('key1', 'val1', 'key2', 'val2')
query_tuple = ('name', 'John', 'age', '25', 'city', 'Hanoi')
config = dict(zip(iter(query_tuple), iter(query_tuple)))
print(config) # {'name': 'John', 'age': '25', 'city': 'Hanoi'}