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

Xử lý key thiếu trong Dictionary Python

Truy cập key không tồn tại trong dict ném KeyError. Có 3 cách xử lý an toàn.

Vấn đề

country_dict = {'India': 'IN', 'Australia': 'AU', 'Brazil': 'BR'}
print(country_dict['Canada'])  # KeyError: 'Canada'

Cách 1: dict.get(key, default) – Khuyên dùng

print(country_dict.get('Australia', 'Not Found'))  # AU
print(country_dict.get('Canada', 'Not Found'))     # Not Found
# Dict không thay đổi

Cách 2: dict.setdefault(key, default)

country_dict.setdefault('Canada', 'Not Present')
print(country_dict['Canada'])  # Not Present
print(country_dict)            # {'India':'IN', 'Australia':'AU', 'Brazil':'BR', 'Canada':'Not Present'}
# Thêm key mới vào dict!

Cách 3: collections.defaultdict

from collections import defaultdict

# Factory function trả giá trị mặc định
d = defaultdict(lambda: 'Key Not Present')
d['India'] = 'IN'
d['Australia'] = 'AU'
print(d['Australia'])  # AU
print(d['Canada'])     # Key Not Present (tự tạo entry)

# Dùng cho counting/grouping
dd = defaultdict(int)
for ch in "hello":
    dd[ch] += 1
print(dict(dd))  # {'h':1, 'e':1, 'l':2, 'o':1}

dl = defaultdict(list)
for w in ['apple','ant','bat']:
    dl[w[0]].append(w)
print(dict(dl))  # {'a':['apple','ant'], 'b':['bat']}

So sánh

Phương phápThay đổi dict?Trường hợp dùng
get()KhôngTra cứu an toàn, không muốn tạo key
setdefault()Có (nếu key thiếu)Khởi tạo giá trị mặc định một lần
defaultdictCó (tự động)Counting, grouping, nested dict

Python 3.8+: Walrus operator

if (val := country_dict.get('Canada')) is not None:
    print(val)
else:
    print("Missing")