Restructure dictionary (Python 2.5)
Tim Chase
python.list at tim.thechases.com
Mon Mar 2 10:19:08 EST 2009
> I tried this code:
> old_dict = {'xyz':['a','b','c'],'baz':['c','d']}
> new_dict = {}
> for dkey, vallist in old_dict.iteritems():
> for val in vallist:
> if val in new_dict:
> theset = new_dict[val]
> theset.add(dkey)
> new_dict[val] = theset
> else:
> new_dict[val] = set([dkey])
> print new_dict
>
> Which yields the output {'a': set(['xyz']), 'c': set(['xyz', 'baz']),
> 'b': set(['xyz']), 'd': set(['baz'])}, so it seems to work but I have a
> feeling this is a crappy solution that's underusing Python. Please
> enlighten me of a better way!
In python2.5, collections.defaultdict was added which could clean
this up a bit:
import collections
# using a set to remove duplication
new_dict = collections.defaultdict(set)
for dkey, vallist in old_dict.iteritems():
for val in vallist:
new_dict[val].add(dkey)
# using a list to keep all keys
new_dict = collections.defaultdict(list)
for dkey, vallist in old_dict.iteritems():
for val in vallist:
new_dict[val].append(dkey)
If you're working in pre-2.5 python, you could use
new_dict = {}
...
# use a set()
new_dict.setdefault(val, set()).add(dkey)
# use a list()
new_dict.setdefault(val, []).append(dkey)
-tkc
More information about the Python-list
mailing list