Python Grouping Data With Dictionaries
Grouping sorts items into buckets by a shared trait. A dict of lists holds one bucket per trait.
Group words by length
Each word joins the bucket for its length. Three-letter words sit apart from four-letter words.
words = ["fig", "pear", "kiwi", "plum"]
groups = {}
for word in words:
size = len(word)
if size not in groups:
groups[size] = []
groups[size].append(word)
print(groups)Group names by first letter
Each name joins the bucket for its first letter. Ada and Amy share the bucket for a.
names = ["ada", "amy", "bob", "cy"]
groups = {}
for name in names:
letter = name[0]
if letter not in groups:
groups[letter] = []
groups[letter].append(name)
print(groups)Fetch one bucket
groups["a"] gives the whole bucket for a. Its length is 2.
groups = {"a": ["ada", "amy"], "b": ["bob"]}
print(groups["a"])
print(len(groups["a"]))Example
books = [("Dune", "scifi"), ("Emma", "classic"), ("Foundation", "scifi"), ("Pride", "classic"), ("Neuromancer", "scifi")]
by_genre = {}
for title, genre in books:
if genre not in by_genre:
by_genre[genre] = []
by_genre[genre].append(title)
print(by_genre)
print("Scifi:", by_genre["scifi"])
print("Classic count:", len(by_genre["classic"]))Key points
- Group: items sorted into buckets by a shared trait
- Use a dict of lists, with one list per bucket
- Use if key not in groups to start a new empty bucket
- Append each item to the bucket that matches its trait
- A bucket holds every item with that trait, in the order they arrived
- Use groups[key] to fetch one whole bucket
- The keys of the groups dict are the traits that appeared.
In this example, the list holds five books with a genre each. The loop puts each title in the bucket for its genre. The scifi bucket holds three titles, and the classic bucket holds two. The classic count of 2 proves both classic titles landed in one bucket.
Note
A new bucket starts empty, and the first item for that trait creates it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What starts a new bucket in the grouping loop?