Trong bài này, chúng ta sẽ học cách sử dụng dictionary comprehension trong Python. Nếu bạn đã quen với list comprehension, dictionary comprehension sẽ rất dễ nắm bắt.
Cú pháp chung
{key: value for item in iterable}
Các trường hợp phổ biến
1. Tạo dict từ range: key là số, value là bình phương
squares = {i: i ** 2 for i in range(10)}
print(squares)
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
2. Tạo dict từ 2 list song song với zip()
keys = ['a', 'b', 'c', 'd', 'e']
values = [1, 2, 3, 4, 5]
dictionary = {key: value for (key, value) in zip(keys, values)}
print(dictionary)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
3. Tạo dict từ 1 list với enumerate() (index làm key)
values = ['a', 'b', 'c', 'd', 'e']
dictionary = {key: value for (key, value) in enumerate(values)}
print(dictionary)
# {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}
Kết luận
Dictionary comprehension giúp code ngắn gọn, Pythonic và dễ đọc. Hãy áp dụng mọi khi có thể để thạo kỹ thuật này.