Unique values per key

EasyCollections Programs · 7 of 20

Write a Python program that collects the unique cities each customer ordered from.

Advertisement
Output
{'asha': ['Mumbai', 'Pune'], 'ravi': ['Delhi']}

Approach

  1. defaultdict(set).

Solution

Python
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.

More collections programs

← All 20 Collections Programs

Leave a Comment