SaltyCrane Blog — Notes on JavaScript and web development

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.

Comments


#1 Parand commented on :

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 :

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


#3 Joe Wang commented on :

Good tips there!


#4 kln commented on :

Thanks, I'm new to python and It was very useful for me.


#5 Walid commented on :

thanks all, these are very useful idioms, especially the one with collections. what would be the overhead if any? I like the clarity of the defaultdict, over the non obvious name of setdefault


#6 Lukas commented on :

Thank you for your example!