Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert sets to frozensets as values of a dictionary

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.

like image 290
Björn Pollex Avatar asked Jun 14 '10 13:06

Björn Pollex


People also ask

Can you convert a set to a dictionary in Python?

The dict() can be used to take input parameters and convert them to a dictionary. We also use the zip function to group the keys and values together which finally become the key value pair in the dictionary.

Can I use a set as a dictionary key?

Is it safe to use a frozenset as a dict key? Yes. According to the docs, Frozenset is hashable because it's immutable. This would imply that it can be used as the key to a dict, because the prerequisite for a key is that it is hashable.

How do you convert a set to Frozenset?

The frozenset() function returns an immutable frozenset object initialized with elements from the given iterable. Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.

How do you convert a variable to a dictionary?

The variable name is placed inside the dict, which will transform them into keys, and the eval() function will extract the value of the variable from the key and create the correspondent key-value dict item (2). That's it, That simple!


2 Answers

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])}
like image 147
krawyoti Avatar answered Oct 02 '22 12:10

krawyoti


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()))
like image 23
Tamás Avatar answered Oct 02 '22 11:10

Tamás