Excellent! Another frequent application of dictionaries is element grouping. Take a look:
names = ['John', 'Mary', 'Alice', 'Kate', 'Michael', 'Samantha', 'Adrian', 'Gray']
groups = {}
for name in names:
key = len(name)
if key not in groups:
groups[key] = []
groups[key].append(name)
print(groups)
Result:
{4: ['John', 'Mary', 'Kate', 'Gray'], 5: ['Alice'], 7: ['Michael'], 8: ['Samantha'], 6: ['Adrian']}
In the example above, we have a list of names (the names
variable) and we want to group them based on name length. To that end, we create an empty dictionary (groups
). The keys in this dictionary are the various name lengths, and the values are lists of matching names. Inside our for
loop, we check each name's length. If the length is not an existing key in the dictionary, we create such a key and initialize it with an empty list. Then we append the given name to a given key represented as the name's length.