01 / 07
The shape you used to write for grouping
Say you want fruit gathered by how many letters it has. Making an empty dictionary and running a for over it is the same as before.
This time, though, the values are lists. So when a key is not there yet, you have to put an empty list in first before you can append.
Those three lines of if follow you around every time.
fruits = ["apple", "plum", "melon", "pear", "grape"]groups = {}for f in fruits: n = len(f) if n not in groups: groups[n] = [] groups[n].append(f)print(groups)Result
{5: ['apple', 'melon', 'grape'], 4: ['plum', 'pear']}