Python Practice › Collections Programs › Program 7
Unique values per key
Write a Python program that collects the unique cities each customer ordered from.
Output
{'asha': ['Mumbai', 'Pune'], 'ravi': ['Delhi']}Approach
defaultdict(set).
Solution
from collections import defaultdict orders = [("asha", "Pune"), ("ravi", "Delhi"), ("asha", "Mumbai"), ("asha", "Pune")]cities = defaultdict(set)for customer, city in orders: cities[customer].add(city)print({k: sorted(v) for k, v in cities.items()})Output
{'asha': ['Mumbai', 'Pune'], 'ravi': ['Delhi']}Learn the concept
New to this topic? Read the lesson, then come back.