0

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))
}
Wychh
  • 469
  • 3
  • 11

1 Answers1

4

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.

Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
  • `d = {frozenset(t) for t in tupl}` seems to give me: `{frozenset({2, 10, 6, 7}), frozenset({38, 34, 35, 30})}` instead of: `{frozenset((2, 10, 6, 7)), frozenset((38, 34, 35, 30}))}` The changing of the `{}` to `()` is a subtle difference, but seems to make a difference. Any suggestions would be great? Also, thanks for the original reply. – Wychh Jul 12 '19 at 14:41
  • 1
    @Wychh: that's entirely correct. You can't have a `frozenset((2, 10, 6, 7))` object. Sets are unordered, and are not tuples. The representation of `frozenset()` objects reflect this by showing you set notation when they are printed. – Martijn Pieters Jul 12 '19 at 14:42
  • 1
    @Wychh: if the objects must be ordered, don't use a `frozenset()`, put the tuples in the outer set directly. You could do that in a single step with `set(tupl)`. – Martijn Pieters Jul 12 '19 at 14:42