I have a frozenset given as x = frozenset({"a":1,"b":2})
. I am not able to figure out a way to be able to access the items in the dict. Is there a way to unfreeze the frozenset? Given below is the error I get.
In [1]: x = frozenset({"a":1,"b":2})
In [2]: x
Out[2]: frozenset({'a', 'b'})
In [3]: x["a"]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-c47cedd3f38d> in <module>()
----> 1 x["a"]
TypeError: 'frozenset' object has no attribute '__getitem__'
Any help greatly appreciated.
The frozenset
constructor takes an iterable! As mentioned in the comments, when you iterate a dict
, you are only iterating its keys, therefore the values are lost.
x = frozenset({"a": 1,"b": 2})
# frozenset(['a', 'b'])
You can create it form the dict
's items though:
x = frozenset({"a": 1, "b": 2}.items())
# frozenset([('a', 1), ('b', 2)])
Now you can simply turn it back into a dict
:
d = dict(x)
# {'a': 1, 'b': 2}