from collections import defaultdict data = [ {'name': 'Alice', 'city': 'New York'}, {'name': 'Bob', 'city': 'London'}, {'name': 'Charlie', 'city': 'New York'}, {'name': 'David', 'city': 'London'}, {'name': 'Eve', 'city': 'Paris'} ] # Group people by city grouped_by_city = defaultdict(list) for item in data: grouped_by_city[item['city']].append(item['name']) # Convert to a regular dict for output if needed result = dict(grouped_by_city) print(result) # Expected: {'New York': ['Alice', 'Charlie'], 'London': ['Bob', 'David'], 'Paris': ['Eve']} # Example with a different default_factory word_counts = defaultdict(int) sentence = "hello world hello python" for word in sentence.split(): word_counts[word] += 1 print(dict(word_counts)) # Expected: {'hello': 2, 'world': 1, 'python': 1}