Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

Python setdefault example

I always forget how to use Python's setdefault dictionary operation so here is a quick example.

What I want:

DATA_SOURCE = (('key1', 'value1'),
               ('key1', 'value2'),
               ('key2', 'value3'),
               ('key2', 'value4'),
               ('key2', 'value5'),)

newdata = {}
for k, v in DATA_SOURCE:
    if newdata.has_key(k):
        newdata[k].append(v)
    else:
        newdata[k] = [v]
print newdata

Results:

{'key2': ['value3', 'value4', 'value5'], 'key1': ['value1', 'value2']}

Better way using setdefault:

newdata = {}
for k, v in DATA_SOURCE:
    newdata.setdefault(k, []).append(v)
print newdata

The results are the same.

3 Comments — feed icon Comments feed for this post


#1 Parand commented on 2010-02-10:

Don't forget defaultdict:

from collections import defaultdict
newdata = defaultdict(list)
DATA_SOURCE = (('key1', 'value1'),
           ('key1', 'value2'),
           ('key2', 'value3'),
           ('key2', 'value4'),
           ('key2', 'value4'),)
for k, v in DATA_SOURCE: newdata[k].append(v)

#2 Eliot commented on 2010-02-10:

Thanks Parand! I had thought there a trick using defaultdict also, but I couldn't remember.


#3 Joe Wang commented on 2010-02-20:

Good tips there!

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Linode