Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Adding an Entry to a Dictionary

Credit: Alex Martelli

Problem

Working with a dictionary D, you need to use the entry D[k] if it’s already present, or add a new D[k] if k isn’t yet a key in D.

Solution

This is what the setdefault method of dictionary objects is for. Say we’re building a word-to-page numbers index. A key piece of code might be:

theIndex = {}
def addword(word, pagenumber):
    if theIndex.has_key(word):
        theIndex[word].append(pagenumber)
    else:
        theIndex[word] = [pagenumber]

Good Pythonic instincts suggest substituting this “look before you leap” pattern with an “easier to get permission” pattern (see Recipe 5.4 for a detailed discussion of these phrases):

def addword(word, pagenumber):
    try: theIndex[word].append(pagenumber)
    except KeyError: theIndex[word] = [pagenumber]

This is just a minor simplification, but it satisfies the pattern of “use the entry if it is already present; otherwise, add a new entry.” Here’s how using setdefault simplifies this further:

def addword(word, pagenumber):
    theIndex.setdefault(word, []).append(pagenumber)

Discussion

The setdefault method of a dictionary is a handy shortcut for this task that is especially useful when the new entry you want to add is mutable. Basically, dict.setdefault(k, v) is much like dict.get(k, v), except that if k is not a key in the dictionary, the setdefault method assigns dict[k]=v as a side effect, in addition to returning v. (get would just return v, without affecting dict in any way.) Therefore, setdefault is appropriate ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata