nathanwailes

Defaultdicts

Jun 9th, 2024
392
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. """
  2. """
  3.  
  4. from collections import defaultdict
  5.  
  6. # Creating a defaultdict with int
  7. int_dict = defaultdict(int)
  8.  
  9. # Adding elements
  10. int_dict['a'] += 1    # Increments the value of 'a' by 1
  11. int_dict['b'] += 2    # Increments the value of 'b' by 2
  12.  
  13. # Creating a defaultdict with list
  14. list_dict = defaultdict(list)
  15.  
  16. # Adding elements
  17. list_dict['a'].append(1)    # Appends 1 to the list associated with 'a'
  18. list_dict['b'].append(2)    # Appends 2 to the list associated with 'b'
  19.  
  20. # Creating a defaultdict with a custom default factory
  21. def default_value():
  22.     return 'default'
  23.  
  24. custom_dict = defaultdict(default_value)
  25.  
  26. # Accessing elements
  27. print(custom_dict['a'])    # Accessing a non-existent key returns 'default'
  28. custom_dict['b'] = 'value'
  29. print(custom_dict['b'])    # Accessing an existing key returns 'value'
  30.  
  31. # Iterating through defaultdict
  32. for key, value in int_dict.items():
  33.     print(f"{key}: {value}")  # Prints each key-value pair in int_dict
  34.  
  35. for key, value in list_dict.items():
  36.     print(f"{key}: {value}")  # Prints each key-value pair in list_dict
  37.  
  38. # Checking for existence of a key (gotcha)
  39. # Accessing a non-existent key in defaultdict will create the key with the default value
  40. print('c' in int_dict)  # False, 'c' does not exist
  41. _ = int_dict['c']       # Accessing 'c', which creates it with default value 0
  42. print('c' in int_dict)  # True, 'c' now exists
  43.  
  44. # Example usage
  45. print("int_dict:", int_dict)
  46. print("list_dict:", list_dict)
  47. print("custom_dict:", custom_dict)
  48.  
  49. # Showing the gotcha
  50. # The gotcha with defaultdict is that accessing a non-existent key creates it with the default value.
  51. another_dict = defaultdict(list)
  52. print("Before accessing a non-existent key:", another_dict)
  53. print(another_dict['new_key'])  # Accessing 'new_key', which creates it with default value (an empty list)
  54. print("After accessing a non-existent key:", another_dict)
  55.  
  56. # Example demonstrating common use case of defaultdict with lists
  57. word_count = defaultdict(int)
  58. words = "the quick brown fox jumps over the lazy dog".split()
  59. for word in words:
  60.     word_count[word] += 1
  61. print("Word count:", word_count)
  62.  
Advertisement
Add Comment
Please, Sign In to add comment