Home > Software engineering >  Convert a frozenset to a dictionary in python
Convert a frozenset to a dictionary in python

Time:03-07

I have the following frozenset:

f_set = [frozenset({8, 14, 15, 18}), frozenset({1, 2, 3, 7, 8}), frozenset({0, 4, 5})]

I need to convert f_set into a dictionary as the following

  • For the first set, I need the dictionary to have a value of 0.
  • For the second set, I need the dictionary to have a value of 1.
  • For the third set, I need the dictionary to have a value of 2.

Now, in case some keys are existed in multiple set, assign a new values to them. In this case 8 existed in both set 1 and set 2, so assign a value of 3.

dict1 = {8:3, 14:0, 15:0, 18:0, 1:1, 2:1, 3:1, 7:1, 0:2, 4:2, 5:2}

Note: my actual f_set contains more than three sets, so I'd like to avoid doing that manually.

CodePudding user response:

You can use dict comprehension with enumerate:

f_set = [frozenset({8, 14, 15, 18}), frozenset({1, 2, 3, 7, 8}), frozenset({0, 4, 5})]

dict1 = {x: i for i, s in enumerate(f_set) for x in s}
print(dict1)
# {8: 1, 18: 0, 14: 0, 15: 0, 1: 1, 2: 1, 3: 1, 7: 1, 0: 2, 4: 2, 5: 2}

Note that, if the sets are not mutually disjoint, some keys will be discarded, since a dict cannot have duplicate keys.

CodePudding user response:

You can simply loop over the frozensets to set each of them in an output dictionary:

output = dict()
    
for i in range(len(f_set)):
    for s in f_set[i]:
        output[s] = i

Note although the order may be different from what you have, order shouldn't matter in the dictionary.

  • Related