Using Python collections defaultdict, OrderedDict, and Sorting Techniques
This article demonstrates how to use Python's collections module, including defaultdict for grouping and counting, OrderedDict for maintaining insertion order, and various sorting techniques for dictionaries and lists of dictionaries using sorted and operator.itemgetter.
This guide introduces advanced usage of the Python collections module, focusing on defaultdict , OrderedDict , and sorting methods for dictionaries and dictionary lists.
1. defaultdict for mapping multiple values
Given a list of key‑value pairs, a normal dict can store only one value per key. By using defaultdict(list) (or defaultdict(set) ), each key can accumulate multiple values automatically.
<code>l = [('a',2),('b',3),('a',1),('b',4),('a',3),('a',1),('b',3)]
from collections import defaultdict
d = defaultdict(list)
for key, value in l:
d[key].append(value)
# Result: defaultdict(list, {'a': [2, 1, 3, 1], 'b': [3, 4, 3]})
</code>If you need unique values, replace list with set . The same pattern works for counting occurrences by using defaultdict(int) :
<code>from collections import defaultdict
objs = [{'F29958SVDK6': 12}, {'F29958SVDK6': 12}, {'F29958SVDK6': 12}, {'F29958SVDK6': 12}, {'F29958SVDK6': 12}]
d = defaultdict(int)
for obj in objs:
for key, value in obj.items():
d[key] += value
# Result: defaultdict(int, {'F29958SVDK6': 60})
</code>2. OrderedDict for preserving insertion order
Although regular dicts are ordered since Python 3.7, the classic OrderedDict still provides explicit methods such as move_to_end and popitem .
<code>from collections import OrderedDict
d = OrderedDict()
d['bar'] = 2
d['non'] = 8
d['sek'] = 5
# Move 'bar' to the end
d.move_to_end('bar')
# d is now OrderedDict([('non', 8), ('sek', 5), ('bar', 2)])
# Remove the first item
first_item = d.popitem(last=False) # ('non', 8)
</code>3. Sorting dictionaries
The built‑in sorted function can order dictionary items by key or by value.
<code>d = {'b': 3, 'a': 4, 'c': 2, 'd': 1}
# Sort by key
sorted_by_key = sorted(d.items(), key=lambda i: i[0])
# [('a', 4), ('b', 3), ('c', 2), ('d', 1)]
# Sort by value
sorted_by_value = sorted(d.items(), key=lambda i: i[1])
# [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
</code>4. Sorting a list of dictionaries
When you have a list of dicts, operator.itemgetter makes it easy to sort by one or multiple fields.
<code>from operator import itemgetter
rows = [
{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
]
# Sort by first name
rows_by_fname = sorted(rows, key=itemgetter('fname'))
# Sort by uid
rows_by_uid = sorted(rows, key=itemgetter('uid'))
# Sort by last name then first name
rows_by_lfname = sorted(rows, key=itemgetter('lname', 'fname'))
</code>These techniques cover common advanced dictionary operations in Python, helping you group data, maintain order, and perform flexible sorting.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.