Python Sorting and Grouping Dictionaries
What you will learn
- Sorting keys, values and pairs, and breaking ties
- Finding the top n items
- Grouping with
setdefaultanddefaultdict - Counting with
Counter itertools.groupby, and why it needs sorted input- Totals, averages and the best item per group
1. Sorting a dictionary
A dictionary keeps insertion order (lesson 9.5), so to see it in another order you sort the keys, the values or the pairs and loop over the result. The examples use these made-up scores:
scores = {"Rina": 90, "Sam": 75, "Lee": 82, "Mia": 82}
print(sorted(scores))
print(sorted(scores, reverse=True))
print(sorted(scores.values()))
print(sorted(scores.items()))
['Lee', 'Mia', 'Rina', 'Sam']
['Sam', 'Rina', 'Mia', 'Lee']
[75, 82, 82, 90]
[('Lee', 82), ('Mia', 82), ('Rina', 90), ('Sam', 75)]
| You sort | You get |
|---|---|
sorted(d) |
the keys, in order |
sorted(d.values()) |
the values |
sorted(d.items()) |
the (key, value) pairs, by key then by value |
Sorting by value
Use key= (lesson 7.4). scores.get gives the value of each key:
print(sorted(scores, key=scores.get))
print(sorted(scores, key=scores.get, reverse=True))
print(sorted(scores, key=lambda n: (-scores[n], n)))
['Sam', 'Lee', 'Mia', 'Rina']
['Rina', 'Lee', 'Mia', 'Sam']
['Rina', 'Lee', 'Mia', 'Sam']
Lee and Mia both have 82: a tie. The sort is stable (lesson 7.4), so tied keys stay in their original order. The third form makes the tie-break explicit: highest score first (the minus sign), then names A to Z.
To get a dictionary back in the new order, build it from the sorted pairs:
print(dict(sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))))
{'Rina': 90, 'Lee': 82, 'Mia': 82, 'Sam': 75}
Quick check: what does `max(scores, key=scores.get)` return?
The key with the biggest value: "Rina".
2. The top n
import heapq
print(heapq.nlargest(2, scores, key=scores.get))
print(heapq.nsmallest(2, scores.items(), key=lambda kv: kv[1]))
print(sorted(scores.items(), key=lambda kv: kv[1])[-2:])
['Rina', 'Lee']
[('Sam', 75), ('Lee', 82)]
[('Mia', 82), ('Rina', 90)]
heapq.nlargest(n, data, key=...)andnsmallestreturn thenbest items. They are faster than sorting everything whennis small and the data is big.- A sorted slice works too, but it sorts everything.
If you need only the very best, max(...) is simpler: [n for n in scores if scores[n] == max(scores.values())] lists all of them when there is a tie (here ["Rina"]).
3. Grouping
Grouping means collecting items under a key. Throughout this section we group these made-up staff records:
people = [
{"name": "Rina", "dept": "IT", "pay": 50},
{"name": "Sam", "dept": "HR", "pay": 40},
{"name": "Lee", "dept": "IT", "pay": 60},
{"name": "Mia", "dept": "HR", "pay": 45},
{"name": "Tom", "dept": "OPS", "pay": 30},
]
With setdefault (lesson 9.2):
by_dept = {}
for p in people:
by_dept.setdefault(p["dept"], []).append(p["name"])
print(by_dept)
{'IT': ['Rina', 'Lee'], 'HR': ['Sam', 'Mia'], 'OPS': ['Tom']}
4. defaultdict: a dictionary with a default
collections.defaultdict is a dictionary that creates a missing value by itself, using a factory function you give it. That removes the "is the key there yet?" step (the Python documentation shows the same idea):
from collections import defaultdict
dd = defaultdict(list)
for p in people:
dd[p["dept"]].append(p["name"])
print(dict(dd))
{'IT': ['Rina', 'Lee'], 'HR': ['Sam', 'Mia'], 'OPS': ['Tom']}
The first time dd["IT"] is used, the factory list() makes an empty list, and the loop appends to it. Pick the factory to fit the job:
| Factory | A missing key starts as | Use for |
|---|---|---|
list |
[] |
grouping items |
int |
0 |
counting |
float |
0.0 |
totalling |
set |
an empty set | unique items per group |
lambda: "n/a" |
any value you choose | a default value |
cnt = defaultdict(int)
total = defaultdict(int)
for p in people:
cnt[p["dept"]] += 1
total[p["dept"]] += p["pay"]
print(dict(cnt))
print(dict(total))
print({d: total[d] / cnt[d] for d in total})
{'IT': 2, 'HR': 2, 'OPS': 1}
{'IT': 110, 'HR': 85, 'OPS': 30}
{'IT': 55.0, 'HR': 42.5, 'OPS': 30.0}
A group of groups uses a lambda as the factory (lesson 11.7):
nested = defaultdict(lambda: defaultdict(int))
nested["IT"]["Rina"] += 1
nested["IT"]["Rina"] += 1
nested["HR"]["Sam"] += 1
print({k: dict(v) for k, v in nested.items()})
{'IT': {'Rina': 2}, 'HR': {'Sam': 1}}
The defaultdict trap
Reading a missing key creates it. Testing with in or get does not:
d = defaultdict(int)
print(d["missing"])
print(dict(d))
print("other" in d, d.get("zzz"), len(d))
0
{'missing': 0}
False None 1
So a typo such as d["totl"] quietly adds a new key instead of raising a KeyError. When you are finished grouping, convert the result back to a plain dictionary with dict(d) so that later mistakes are caught. A defaultdict() with no factory behaves like a normal dictionary and raises KeyError.
5. Counter: counting made easy
collections.Counter is a dictionary made for counting. Give it any collection, and it counts the items:
from collections import Counter
text = "the cat and the hat and the bat"
c = Counter(text.split())
print(c)
print(c["the"], c["missing"])
print(c.most_common(2))
Counter({'the': 3, 'and': 2, 'cat': 1, 'hat': 1, 'bat': 1})
3 0
[('the', 3), ('and', 2)]
- A missing item counts as
0, without being added. most_common(n)gives the topnas pairs, most frequent first. With non, it gives all.sum(c.values())is the total of the counts. Python 3.10 and later also hasc.total().
More ways to use it, from the Python documentation:
c2 = Counter("aab")
c2.update("abc")
print(c2)
c2.subtract("aa")
print(c2)
print(list(Counter("aab").elements()))
Counter({'a': 3, 'b': 2, 'c': 1})
Counter({'b': 2, 'a': 1, 'c': 1})
['a', 'a', 'b']
update(...)adds counts (unlike a dictionary'supdate, which replaces).subtract(...)takes counts away (they may go to zero or below).elements()repeats each item by its count.
Counters can be added, subtracted and compared:
a = Counter(a=3, b=1)
b = Counter(a=1, b=2)
print(a + b)
print(a - b)
print(a & b)
print(a | b)
print(Counter("listen") == Counter("silent"))
Counter({'a': 4, 'b': 3})
Counter({'a': 2})
Counter({'a': 1, 'b': 1})
Counter({'a': 3, 'b': 2})
True
+ adds, - subtracts (and drops zero or negative results), & takes the smaller count, | the larger. The last line is the classic anagram test: two words are anagrams when they have the same letter counts.
6. itertools.groupby
itertools.groupby(data, key=...) walks through the data and starts a new group each time the key changes. It does not gather items from far apart, so the data must be sorted by the same key first:
from itertools import groupby
rows = sorted(people, key=lambda p: p["dept"])
for dept, group in groupby(rows, key=lambda p: p["dept"]):
print(dept, [p["name"] for p in group], end="; ")
print()
HR ['Sam', 'Mia']; IT ['Rina', 'Lee']; OPS ['Tom'];
Without sorting, the same key can appear more than once:
pairs = [("a", 1), ("b", 2), ("a", 3)]
print([(k, [v for _, v in g]) for k, g in groupby(pairs, key=lambda p: p[0])])
print([(k, [v for _, v in g]) for k, g in groupby(sorted(pairs), key=lambda p: p[0])])
[('a', [1]), ('b', [2]), ('a', [3])]
[('a', [1, 3]), ('b', [2])]
groupby is perfect for runs of equal items, such as "aabbbc", giving [('a', 2), ('b', 3), ('c', 1)]. For grouping unsorted data, defaultdict(list) is simpler.
7. The best item per group
Keep the best record seen so far for each key:
best = {}
for p in people:
if p["dept"] not in best or p["pay"] > best[p["dept"]]["pay"]:
best[p["dept"]] = p
print({d: p["name"] for d, p in best.items()})
{'IT': 'Lee', 'HR': 'Mia', 'OPS': 'Tom'}
Here the highest-paid person in each department is shown.
Worked example: a department report
Using people, print each department with its headcount, total pay and average pay, from the largest total down, then draw a bar chart of the headcounts.
from collections import defaultdict
headcount = defaultdict(int)
total = defaultdict(int)
for p in people:
headcount[p["dept"]] += 1
total[p["dept"]] += p["pay"]
for dept in sorted(total, key=total.get, reverse=True):
avg = total[dept] / headcount[dept]
print(f"{dept:<4} {headcount[dept]} people total {total[dept]:>4} average {avg:.1f}")
for dept in sorted(headcount):
print(f"{dept:<4}", "#" * headcount[dept])
IT 2 people total 110 average 55.0
HR 2 people total 85 average 42.5
OPS 1 people total 30 average 30.0
HR ##
IT ##
OPS #
| Step | Tool |
|---|---|
| headcount and total per department | two defaultdict(int) counters |
| order by total pay | sorted(total, key=total.get, reverse=True) |
| average | total divided by headcount |
| alignment | format codes :<4 and :>4 (lesson 4.6) |
The names, departments and pay are made up.
Common mistakes
- Expecting
sorted(d)to sort by value. It sorts the keys; usekey=d.get. - Forgetting that
sortedreturns a list, not a dictionary. - Reading a missing key of a
defaultdict, which creates it. - Using
groupbyon unsorted data. - Using
dict.updatewhen you meant to add counts.Counter.updateadds. - Leaving a
defaultdictin place after grouping; convert withdict(...).
Key takeaways
- Sort keys with
sorted(d), values withsorted(d.values()), and by value withsorted(d, key=d.get); tied items keep their order. heapq.nlargestandnsmallestfind the topn;max(d, key=d.get)finds the best key.- Group with
setdefault(key, []).append(...)ordefaultdict(list);defaultdict(int)counts anddefaultdict(float)totals. Countercounts, givesmost_common(n), adds and subtracts counts and tests anagrams.groupbyneeds data sorted by the same key; keep the best record per group with a dictionary.
Practice
1. Print the names in scores from the highest score to the lowest.
Show answer
sorted(scores, key=scores.get, reverse=True) gives the names; loop over it to print each one.
2. Count the vowels in "education" with Counter.
Show answer
Counter(c for c in "education" if c in "aeiou") gives Counter({'e': 1, 'u': 1, 'a': 1, 'i': 1, 'o': 1}).
3. Group the words ["ant", "bee", "bat", "ape"] by their first letter.
Show answer
from collections import defaultdict
groups = defaultdict(list)
for w in ["ant", "bee", "bat", "ape"]:
groups[w[0]].append(w)
The result is {'a': ['ant', 'ape'], 'b': ['bee', 'bat']}.
4. What does Counter("aab") - Counter("ab") give?
Show answer
Counter({'a': 1}). The b count drops to zero and is left out.
5. Why does groupby need sorted data?
Show answer
It starts a new group each time the key changes and never looks back. Equal keys that are not next to each other end up in separate groups.
6. What is the danger of d["total"] on a defaultdict(int) when the key is a typo?
Show answer
Reading a missing key creates it with 0, so the typo silently adds a wrong key instead of raising a KeyError.