Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- """
- from collections import defaultdict
- # Creating a defaultdict with int
- int_dict = defaultdict(int)
- # Adding elements
- int_dict['a'] += 1 # Increments the value of 'a' by 1
- int_dict['b'] += 2 # Increments the value of 'b' by 2
- # Creating a defaultdict with list
- list_dict = defaultdict(list)
- # Adding elements
- list_dict['a'].append(1) # Appends 1 to the list associated with 'a'
- list_dict['b'].append(2) # Appends 2 to the list associated with 'b'
- # Creating a defaultdict with a custom default factory
- def default_value():
- return 'default'
- custom_dict = defaultdict(default_value)
- # Accessing elements
- print(custom_dict['a']) # Accessing a non-existent key returns 'default'
- custom_dict['b'] = 'value'
- print(custom_dict['b']) # Accessing an existing key returns 'value'
- # Iterating through defaultdict
- for key, value in int_dict.items():
- print(f"{key}: {value}") # Prints each key-value pair in int_dict
- for key, value in list_dict.items():
- print(f"{key}: {value}") # Prints each key-value pair in list_dict
- # Checking for existence of a key (gotcha)
- # Accessing a non-existent key in defaultdict will create the key with the default value
- print('c' in int_dict) # False, 'c' does not exist
- _ = int_dict['c'] # Accessing 'c', which creates it with default value 0
- print('c' in int_dict) # True, 'c' now exists
- # Example usage
- print("int_dict:", int_dict)
- print("list_dict:", list_dict)
- print("custom_dict:", custom_dict)
- # Showing the gotcha
- # The gotcha with defaultdict is that accessing a non-existent key creates it with the default value.
- another_dict = defaultdict(list)
- print("Before accessing a non-existent key:", another_dict)
- print(another_dict['new_key']) # Accessing 'new_key', which creates it with default value (an empty list)
- print("After accessing a non-existent key:", another_dict)
- # Example demonstrating common use case of defaultdict with lists
- word_count = defaultdict(int)
- words = "the quick brown fox jumps over the lazy dog".split()
- for word in words:
- word_count[word] += 1
- print("Word count:", word_count)
Advertisement
Add Comment
Please, Sign In to add comment