Search code examples
pythonpython-3.xsetfrozenset

Appending frozensets to a dictionary


I am working with a piece of code (written in python) that accepts an argument of the form:

restricted_bonds = {
    frozenset((0, 10)),
    frozenset((3, 14)),
    frozenset((5, 6))
}

I have a tuple of the form:

tupl = ((0, 5, 6, 1), (4, 5, 6, 8))

where, I want to create a frozenset which can be read as:

d = {frozenset((0, 5, 6, 1)),
     frozenset((4, 5, 6, 8))
}

The idea is to be able to set restricted_bonds = d

I have tried a few variations of:

for i in tupl:
    d[frozenset(i)] = ''

The ideal result will be:

d = {frozenset((0, 5, 6, 1)),
     frozenset((4, 5, 6, 8))
}

Solution

  • You don't have a dictionary. You have set objects; specifically a set() object containing frozenset() objects. These are not artefacts, code has to explicitly make a choice to use these objects. See the section on sets in the Python tutorial.

    frozenset() objects are simply immutable sets; values stored in a set must be hashable, and to be hashable requires that the objects stored are immutable (*). Both set() and frozenset() are built-in types, like str and list and tuple, you can use them directly without imports.

    Just use the set.add() method to add individual values, and set.update() or the |= augmented assignment to add more elements to your set.

    If you just want to create a new set from an arbitrary number of tuples, use a set comprehension (touched upon in the same section of the tutorial):

    tupl = ((0, 5, 6, 1), (4, 5, 6, 8))
    d = {frozenset(t) for t in tupl}
    

    (*): to be exact: the state of an object that is used to determine equality must also be used to determine the hash (equal objects must have the same hash), and the hash must remain stable. Additional attributes associated with an object that are not used to determine equality can be changed at will.