bookBài tập Dictionary - Nâng cao

Các bài tập về Dictionary - Nâng cao

  1. Viết hàm merge_dicts gộp nhiều dictionaries thành một, xử lý conflicts (key trùng).

def merge_dicts(*dicts, strategy="last"):
    # strategy: "last" (giữ giá trị cuối), "first" (giữ giá trị đầu), "list" (gộp thành list)
    pass

# Test
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
dict3 = {"c": 5, "d": 6}

print(merge_dicts(dict1, dict2, dict3))  # {"a": 1, "b": 3, "c": 5, "d": 6}
print(merge_dicts(dict1, dict2, dict3, strategy="list"))  # {"b": [2, 3], "c": [4, 5], ...}
  1. Viết hàm invert_dict đảo ngược dictionary (values thành keys).

def invert_dict(d):
    # Xử lý trường hợp values trùng nhau -> list of keys
    pass

# Test
original = {"a": 1, "b": 2, "c": 1}
inverted = invert_dict(original)
print(inverted)  # {1: ["a", "c"], 2: ["b"]}
  1. Viết hàm flatten_dict làm phẳng nested dictionary.

  1. Viết hàm unflatten_dict chuyển flat dictionary về nested.

  1. Viết hàm dict_diff tìm khác biệt giữa 2 dictionaries.

  1. Viết hàm deep_get truy cập nested dictionary an toàn với default value.

  1. Viết hàm deep_set set giá trị trong nested dictionary, tự động tạo keys nếu chưa có.

  1. Viết hàm filter_dict lọc dictionary theo điều kiện.

  1. Viết hàm map_dict áp dụng function lên values hoặc keys.

  1. Viết hàm group_by nhóm list of dicts theo một key.

  1. Viết hàm dict_path_exists kiểm tra path có tồn tại trong nested dict không.

  1. Viết hàm dict_to_xml chuyển dictionary thành XML string (đơn giản).

  1. Viết hàm normalize_dict chuẩn hóa dictionary (lowercase keys, strip values, etc.).

  1. Viết class DotDict cho phép truy cập dictionary như object attributes.

  1. Viết hàm dict_query query dictionary giống SQL.

  1. Viết hàm dict_aggregate tính toán aggregate functions.

  1. Viết CachedDict - dictionary với cache và TTL.

  1. Viết hàm dict_schema_validate validate dictionary theo schema.

  1. Viết hàm dict_to_object chuyển dictionary thành Python object.

  1. Viết OrderedCounter kết hợp Counter và giữ thứ tự.

  1. Viết hàm dict_compression nén dictionary bằng cách tối ưu keys lặp lại.

  1. Viết MultiDict - dictionary có thể có nhiều values cho một key.

  1. Viết hàm dict_deep_merge merge nested dictionaries recursively.

  1. Viết ConfigDict - dictionary với dot notation và type conversion.

  1. Viết hàm dict_performance_compare so sánh performance của dict operations.

Last updated