Created
April 17, 2015 05:56
-
-
Save jling90/99e46cb423c721a5a20b to your computer and use it in GitHub Desktop.
Default dict example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
fruits = [("berry", "strawberry"), ("citrus", "orange"), \ | |
("citrus", "lemon"), ("stone fruit", "nectarine"), \ | |
("berry", "blue berry") ] | |
# Suppose we want to build a dictionary using the first entry of each tuple as a key... | |
fruit_dict = {} | |
for tup in fruits: | |
if tup[0] not in fruit_dict: | |
fruit_dict[tup[0]] = [tup[1]] | |
else: | |
fruit_dict[tup[0]].append(tup[1]) | |
for fruit_type, fruit in fruit_dict.iteritems(): | |
print fruit_type, ': ', ', '.join(fruit) | |
# Same implementation using defaultdict | |
fruit_dict = defaultdict(list) | |
for tup in fruits: | |
fruit_dict[tup[0]].append(tup[1]) | |
for fruit_type, fruit in fruit_dict.iteritems(): | |
print fruit_type, ': ', ', '.join(fruit) | |
# By way of explanation, defaultdict takes a function (acting as a default value factory). | |
# in this case 'list' is provided. Instead of throwing a key error if a key isn't found, | |
# a new key will have the initial value provided by the factory function. | |
# Here we've specified the function 'list', so whenever we operate on a new key, it takes | |
# an empty list as its default value. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment