F
Fencer
Hello, I have a dictionary that has strings as keys and for each key the
associated value is a list of strings. Many of the lists contain only
one element and a given element may appear for more than one key.
What I need to do now is create a new dictionary where the strings in
the list are keys and their values is a list of which keys in the "old"
dictionary that contained them.
So I want to go from:
aa:[a, b, c]
bb:[c, d]
to
a:[aa]
b:[aa]
c[aa, bb]
d:[bb]
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!
- Fencer
associated value is a list of strings. Many of the lists contain only
one element and a given element may appear for more than one key.
What I need to do now is create a new dictionary where the strings in
the list are keys and their values is a list of which keys in the "old"
dictionary that contained them.
So I want to go from:
aa:[a, b, c]
bb:[c, d]
to
a:[aa]
b:[aa]
c[aa, bb]
d:[bb]
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!
- Fencer