demo_setdefault.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. # 原始数据(每行是个字典)
  2. rows = [
  3. {"label": "fruit", "item": "apple"},
  4. {"label": "fruit", "item": "banana"},
  5. {"label": "vegetable", "item": "carrot"},
  6. {"label": "fruit", "item": "orange"},
  7. {"label": "vegetable", "item": "broccoli"},
  8. ]
  9. buckets = {} # 空字典,用来分组
  10. for row in rows:
  11. label = row["label"]
  12. # print(f'label: {label}')
  13. # 确保 buckets 中有 label 这个键,且值为列表
  14. buckets.setdefault(label, []) # 如果 label 不存在,插入空列表
  15. # print(f"buckets: {buckets}")
  16. buckets[label].append(row["item"]) # 现在可以安全地 append
  17. print(buckets)
  18. '''
  19. buckets.setdefault(label, []) 执行后:
  20. 第一次遇到 "fruit" 时,buckets 中没有这个键,于是插入 "fruit": [],并返回这个空列表。
  21. 第二次遇到 "fruit" 时,键已经存在,直接返回已有的列表(不改变它)。
  22. 接着 buckets[label].append(...) 就把元素追加到对应的列表里。
  23. 这样就不需要先判断 if label not in buckets 再创建列表,一行搞定。
  24. '''
  25. # buckets1 = {}
  26. # for row in rows:
  27. # buckets1.setdefault(row["label"], []).append(row["item"])
  28. #
  29. # print(buckets1)