views:

50

answers:

3

I have dictionary that is built as part of the initialization of my object. I know that it will not change during the lifetime of the object. The dictionary maps keys to sets. I want to convert all the values from sets to frozensets, to make sure they do not get changed. Currently I do that like this:

for key in self.my_dict.iterkeys():
    self.my_dict[key] = frozenset(self.my_dict[key])

Is there a simpler way to achieve this? I cannot build frozenset right away, because I do not how much items will be in each set until i have built the complete dictionary.

A: 

If you have to do it in-place, probably this is the simplest way (almost the same as you posted):

for key, value in self.my_dict.iteritems():
    self.my_dict[key] = frozenset(value)

This a variant which builds a temporary dict:

self.my_dict = dict(((key, frozenset(value)) \
                    for key, value in self.my_dict.iteritems()))
Tamás
A: 

In Python 3, you could use a dictionary comprehension:

d = {k: frozenset(v) for k, v in d.items()}

In Python 2, though, I don't know that there's anything shorter -- this at least feels less "redundant":

for k,v in d.iteritems():
    d[k] = frozenset(v)
Craig Citro
+2  A: 

Given, for instance,

>>> d = {'a': set([1, 2]), 'b': set([3, 4])}
>>> d
{'a': set([1, 2]), 'b': set([3, 4])}

You can do the conversion in place as

>>> d.update((k, frozenset(v)) for k, v in d.iteritems())

With the result

>>> d
{'a': frozenset([1, 2]), 'b': frozenset([3, 4])}
krawyoti