Skip to content

Instantly share code, notes, and snippets.

@victor-iyi
Last active May 4, 2026 09:35
Show Gist options
  • Select an option

  • Save victor-iyi/f8dab736b856ac1f220f787d65dc6046 to your computer and use it in GitHub Desktop.

Select an option

Save victor-iyi/f8dab736b856ac1f220f787d65dc6046 to your computer and use it in GitHub Desktop.
Demonstrating Python's defaultdict
"""
# Using Python's `collections.defaultdict`.
```python
>>> import collections
>>> dct = collections.defaultdict(int)
>>> int()
0
>>> dct['a']
0
>>> dct['b'] += 2
>>> dct
defaultdict(<class 'int'>, {'a': 0, 'b': 2})
>>> # Using custom defaults.
>>> dct2 = collections.defaultdict(lambda: [{}])
>>> dct2['a']
[{}]
>>> dct2['a'].append({'foo': 'bar'})
>>> dct2
defaultdict(<function <lambda> at 0x7f977bf96a60>, {'a': [{}, {'foo': 'bar'}]})
>>> # Creating defaultdict with a vanilla Python's dictionary.
>>> collections.defaultdict(int, {'a': 2, 'b': 3})
defaultdict(<class 'int'>, {'a': 2, 'b': 3})
>>>
```
"""
# Demonstrating Python's default dict.
#
# Problem:
# Produce a mapping from {country: [sorted list of cities]}
import collections
import pprint
# Unsorted cities and countries.
cities_by_coutry = {
'San Mateo': 'US',
'Toronto': 'CA',
'Detroit': 'US',
'London': 'UK',
'Paris': 'FR',
'Seattle': 'US',
'Vancouver': 'CA',
}
################################################################################################
# +--------------------------------------------------------------------------------------------+
# | Method one: Using vanilla Python dictionary.
# +--------------------------------------------------------------------------------------------+
################################################################################################
dct = {}
for city, country in cities_by_country.items():
if country in dct:
dct[country].append(city) # append new city.
else:
dct[country] = [city] # create a new list of cities.
# Sort list of cities.
for cities_list in dct.values():
cities_list.sort()
# Pretty print the output.
pprint.pprint(dct)
################################################################################################
# +--------------------------------------------------------------------------------------------+
# | Method two: Using `collections.defaultdict`.
# +--------------------------------------------------------------------------------------------+
################################################################################################
dct = collections.defaultdict(list)
for city, country in cities_by_country.items():
dct[country].append(city)
# Sort list of cities.
for cities in dct.values():
cities.sort()
pprint.pprint(dct)
################################################################################################
# +--------------------------------------------------------------------------------------------+
# | Method three: Using `dict.setdefault` method.
# +--------------------------------------------------------------------------------------------+
################################################################################################
dct = {}
for city, country in cities_by_country.items():
dct.setdefault(country, []).append(city)
for cities in dct.values():
cities.sort()
pprint(dct)
@johngitahi

Copy link
Copy Markdown

thanks for writing this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment