categorize_items.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. def categorize_items(items: list) -> dict:
  2. """
  3. Categorizes items from a list into a dictionary.
  4. This function takes a list of mixed integers and strings and returns a
  5. dictionary containing three keys:
  6. - 'integers': A list of all integer items.
  7. - 'strings': A list of all string items.
  8. - 'counts': A dictionary where keys are string representations of
  9. items (e.g., 'i_123' for int, 's_apple' for str) and
  10. values are their frequencies.
  11. Args:
  12. items: A list containing a mix of integers and strings.
  13. Returns:
  14. A dictionary with categorized lists and item counts.
  15. Returns None if the input list is empty.
  16. """
  17. if not items:
  18. return None
  19. integers = []
  20. strings = []
  21. counts = {}
  22. for item in items:
  23. if isinstance(item, int):
  24. integers.append(item)
  25. key = 'i_{}'.format(item)
  26. counts[key] = counts.get(key, 0) + 1
  27. elif isinstance(item, str):
  28. strings.append(item)
  29. key = 's_{}'.format(item)
  30. counts[key] = counts.get(key, 0) + 1
  31. return {
  32. 'integers': integers,
  33. 'strings': strings,
  34. 'counts': counts
  35. }
  36. # Example usage (for reference, not part of the agent's task)
  37. if __name__ == '__main__':
  38. data = [1, "apple", 2, "banana", 1, "apple", 3, "cherry"]
  39. result = categorize_items(data)
  40. print("Categorized Items:", result)
  41. # Expected output structure:
  42. # {
  43. # 'integers': [1, 2, 1, 3],
  44. # 'strings': ['apple', 'banana', 'apple', 'cherry'],
  45. # 'counts': {'i_1': 2, 's_apple': 2, 'i_2': 1, 's_banana': 1, 'i_3': 1, 's_cherry': 1}
  46. # }