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.
Related posts
- An example using Python's groupby and defaultdict to do the same task — posted 2014-10-09
- python enum types — posted 2012-10-10
- Python data object motivated by a desire for a mutable namedtuple with default values — posted 2012-08-03
- How to sort a list of dicts in Python — posted 2010-04-02
- How to conditionally replace items in a list — posted 2008-08-22
Comments
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)
Thanks Parand! I had thought there a trick using defaultdict also, but I couldn't remember.
Good tips there!
Thanks, I'm new to python and It was very useful for me.
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
Thank you for your example!